admin管理员组

文章数量:1416059

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>

I'd like to hide everything in .drop-down class excluding <h3> by clicking on <h3>. In this case only .arrow toggleClass works.

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>

I'd like to hide everything in .drop-down class excluding <h3> by clicking on <h3>. In this case only .arrow toggleClass works.

Share Improve this question edited Nov 11, 2014 at 15:50 DreamTeK 34.4k29 gold badges124 silver badges178 bronze badges asked Aug 6, 2013 at 18:21 user2587741user2587741 1994 silver badges14 bronze badges 2
  • Instead of parent(), use .closest() – Dom Commented Aug 6, 2013 at 18:22
  • The only thing in the .drop-down class is the h3 – Chris Rockwell Commented Aug 6, 2013 at 18:25
Add a ment  | 

2 Answers 2

Reset to default 3

Use closest instead of parent

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

parent will only go back 1 level , i.e, the immediate parent. But you gotta get the container that encloses all the 3 elements

So $(this).parent(".drop-down")

supposed to be either

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

or

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

if you need toggle them all but the .drop-down .siblings is just what you need

$("div.drop-down > h3").click(function(){
    var $t = $(this);
    $t.parent().siblings().toggle();
});

本文标签: javascriptthis parent jQueryStack Overflow