切换此内容并使用jQuery自动隐藏其他内容

时间:2015-07-17 14:16:16

标签: jquery

以下jQuery代码切换当前内容:

$(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class content
  $(".heading").click(function()
  {
    $(this).next(".content").slideToggle(500);
  });
});

Demo

我想切换(显示/隐藏)当前内容,同时隐藏具有相同类的其他项目。为此,我添加了" $(" .content")。hide();" (参见here。)但在这种情况下,当我单击当前再次显示的元素时,它将不会切换(隐藏)但会再次显示。

在这种情况下如何处理?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

排除"当前"一个来自hide()

$(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class content
  $(".heading").click(function()
  {
    $(".content").not($(this).next(".content").slideToggle(500)).hide();
  });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/eK8X5/6829/

我意识到这可能看起来很神秘,所以长版本(中间行)是:

 var $target = $(this).next(".content");
 $(".content").not($target).hide();
 $target.slideToggle(500)

注意:如果slideUp()而非hide()其他人,您将获得更好的视觉效果:

e.g。

$(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class content
  $(".heading").click(function()
  {
    $(".content").not($(this).next(".content").slideToggle(500)).slideUp();
  });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/eK8X5/6832/

相关问题