【问题标题】:Multiple slidetoggle divs change text多个滑动切换 div 更改文本
【发布时间】:2015-10-26 11:56:32
【问题描述】:

我有这段代码,它显示了一个配置文件 div onclick 并更改了单击元素的文本。这种情况有多种。

<div class="show" data-target=".open1">View Profile</div>
<div class="info open1">Lorem ipsum</div>

当另一个 div 打开时,之前打开的 div 会关闭。然而,这方面的文字仍然是“密切的个人资料”。我想更改它,以便文本也更改回来。

知道我该怎么做吗?

var $bgs = $('.info');
var $show = $('.show');

$($show).click(function () {
    var $target = $($(this).data('target')).stop(true).slideToggle();
    $bgs.not($target).filter(':visible').stop(true, true).slideUp();

    $(this).click(function(){
        $(this).text(function(_, oldText) {
            return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile';

        });

    });
})

【问题讨论】:

  • 你不需要在 $() 中重新包装 $show - 它已经是一个 jQuery 对象
  • 不需要内部.click(。只需检查文本并更新它。

标签: javascript jquery html css slidetoggle


【解决方案1】:

请检查:

var $bgs = $('.info');
var $show = $('.show');

$show.click(function () {
    var $target = $($(this).data('target')).stop(true).slideToggle();
    var oldOpened = $bgs.not($target).filter(':visible');
    oldOpened.stop(true, true).slideUp();
    if(oldOpened.length > 0){
      var tempClasses = $(oldOpened).attr("class");
      var oldOpenClass = $.trim(tempClasses.replace("info",""));
      var oldOpenerDiv = $("div[data-target='."+oldOpenClass+"']");
      
      $(oldOpenerDiv).text(function(_, oldText) {
        return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile';

       });
    }
  
   $(this).text(function(_, oldText) {
      return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile';

   });
})
.info{
  display:none;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="show" data-target=".open1">View Profile</div>
<div class="info open1">Lorem ipsum 11</div>
<div class="show" data-target=".open2">View Profile</div>
<div class="info open2">Lorem ipsum 22</div>
<div class="show" data-target=".open3">View Profile</div>
<div class="info open3">Lorem ipsum 33</div>

【讨论】:

  • 就这样整理好了。非常感谢
【解决方案2】:

var $bgs = $('.info');
var $show = $('.show');

$show.click(function() {
  var $target = $($(this).data('target')).stop(true).slideToggle();
  $bgs.not($target).filter(':visible').stop(true, true).slideUp();


  $(this).text(function(_, oldText) {
    return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile';

  });

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="show" data-target=".open1">View Profile</div>
<div class="info open1">Lorem ipsum</div>

【讨论】:

  • 为什么是$($show)??还有$($(this).data('target'))。如果您定义了$show,只需使用它:$show.click(function(){...});
  • 你是对的@ding0_d。但他的问题不同,这与他如何编写代码无关。我仍然纠正了它。
  • 感谢@Atul。我已经实现了修改后的代码。当我打开第二个配置文件时,前一个会关闭,但它仍然显示“关闭配置文件”文本。我怎样才能让它回到“查看个人资料”?
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多