javascript - 这个父 jQuery

标签 javascript jquery this parent

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>

我想隐藏 .drop-down 中的所有内容类不包括 <h3>通过点击 <h3> .在这种情况下只有 .arrow toggleClass 有效。

最佳答案

使用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

关于javascript - 这个父 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18087644/

相关文章:

javascript - 为什么在同一语句中调用时括号会保留它

javascript - 简单的 Angularjs 没有显示

javascript - 包含 Alchemy js 的源代码会破坏 Highcharts js

javascript - 在循环中将函数传递给 setTimeout : always the last value?

javascript - Uncaught ReferenceError : height is not defined - Backbone. js

c++ - 派生类的this指针是如何找到成员函数的?

javascript - ionic 无限滚动以显示更多已加载的项目(不是通过 httprequest)

javascript - 绑定(bind)值时日期时间格式太复杂,AngularJS

jquery - “effect”在 jsfiddle 中工作正常,但在实时代码中不起作用([object Object] 没有方法 'effect' )

Javascript:利用对自己的本地引用是否可以接受编码实践?