簡體   English   中英

這個父jQuery

[英]this parent jQuery

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

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

parent 只會返回 1 level ,即直接父級。 但是你必須得到包含所有 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

如果您需要全部切換,但 .drop-down .siblings 正是您所需要的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM