我试图在单击内部嵌套按钮时关闭父容器。在我的 UI 中——我有许多这样的父容器(我在产品类别页面上呈现我的产品目录的预览窗口)。
正如您从我下面的标记中看到的那样——关闭按钮深深地嵌套在 DOM 中。当用户点击关闭按钮时——我需要隐藏()父 Box-1。请记住,我一次最多可以在一个页面上显示 100 种产品(100 盒“Box-1”)。
我的标记如下所示:
<div class="box-1">
<div class="box-2">
<div class="box-3">...</div> <!-- end box-3 -->
<div class="box-4">
<div class="box-5">...</div> <!-- end box-5 -->
<a class="btn-close" href="#">CLOSE</a> <!-- this triggers the close event -->
</div> <!-- end box-4 -->
</div> <!-- end box-2 -->
<div class="box-6">
<div class="box-7">...</div> <!-- end box-7 -->
<div class="box-8">
...
<div class="box-9">...</div> <!-- end box-9 -->
</div> <!-- end box-8 -->
</div> <!-- end box-6 -->
</div> <!-- end box-1 -->
我的问题是——我如何最好(并且最有效地)遍历返回 DOM 以获取“box-1”并发出 .hide() 方法……这是我现有的代码。
<script>
$productsResultItems.delegate('.btn-close', 'click', function (e) {
//box-1
$(this).parents('div.box-1').hide(); // <-- is this the best way?????
e.preventDefault();
</script>
最初,我正在尝试这个——
$this.parents().find('.hover-box-large').hide();
这在 IE7 和 IE8 中被证明是非常慢的。
我发现在选择器中添加更多细节可以将 IE7 的性能提高近 100 倍,但在 IE8 中只快 4 倍:( IE8 仍然需要大约 200 毫秒来关闭父容器。现在所有其他浏览器(Chrome、Safari , Firefox 和 IE7) 在不到 20 毫秒的时间内关闭容器。
$this.parents('div.hover-box-large').hide();
但是有没有更好的选择器方法呢? IE8 不擅长这种向上遍历的任何特殊原因??
最佳答案
最好的使用方法是 closest
, 它找到与选择器匹配的最近的祖先元素:
$this.closest('div.box-1').hide();
关于javascript - 在 jQuery 中向上遍历最有效的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6253735/