这个父级jQuery

3

jQuery

$(".drop-down h3").click(function(e) {
  e.preventDefault();
  $(this).parent(".drop-down").find($("ul")).stop().slideToggle();
  $(this).parent(".drop-down").find($(".divider-aside")).stop().toggle("slow");
  $(this).parent(".drop-down").find($(".arrow")).stop().toggleClass("rotate1 rotate2");
});

HTML

<div id="categories">
  <div class="drop-down">
    <h3>Categories</h3>
  </div>
  <div class="divider-aside"></div>
  <ul>
    <li>123</li>
    <li>12323</li>
    <li>1231</li>
    <li>523</li>
    <li>31</li>
  </ul>
</div>

我希望通过点击<h3>元素,隐藏.drop-down类中除<h3>以外的所有内容。在这种情况下,只有.arrow toggleClass 起作用。


使用.closest()代替parent() - Dom
.drop-down 类中唯一的元素是 h3。 - Chris Rockwell
2个回答

3

使用 closest 代替 parent

$(this).closest("#categories")

父元素只会返回一级,即直接的父元素。但你需要获取包含所有3个元素的容器。

所以 $(this).parent(".drop-down")

应该是以下之一:

$(this).parent().parent()   // this will break if there is an extra
                            // parent container gets added

或者

$(this).closest("#categories") // This will work even if the no of
                               // parent container keep chaning

我会选择留在 - $(this).parent().parent(),非常感谢 :) 我会接受这个答案。 - user2587741
应该使用$(this).closest("#categories")而不是$(this).closest(".categories"),因为@user2587741在示例中使用的是<div id="categories"> - gurtner
@dgurtner 你是对的。一定是我疏忽了。 - Sushanth --

0
如果你需要切换它们所有,但是只想选择 `.drop-down .siblings`。
$("div.drop-down > h3").click(function(){
    var $t = $(this);
    $t.parent().siblings().toggle();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接