在jQuery中遍历的最有效方法是什么

rst*_*rim 5 javascript jquery dom-traversal

单击内部嵌套的按钮时,我正在尝试关闭父容器。在我的UI中-我有许多这样的父容器(我正在产品类别页面上渲染产品目录的预览窗口)。

从下面的标记中可以看到CLOSE按钮深深地嵌套在DOM中。当用户单击“关闭”按钮时,我需要hide()父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 -->
Run Code Online (Sandbox Code Playgroud)

我的问题是-如何最好地(最有效地)遍历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>
Run Code Online (Sandbox Code Playgroud)

最初,我正在尝试-

$this.parents().find('.hover-box-large').hide();
Run Code Online (Sandbox Code Playgroud)

事实证明,这在IE7和IE8中非常慢。

我发现向选择器添加更多细节使IE7的性能提高了近100倍,但在IE8中仅提高了4倍:( IE8仍需要大约200毫秒来关闭父容器。现在所有其他浏览器(Chrome,Safari,Firefox和IE7)在不到20毫秒的时间内关闭容器。

$this.parents('div.hover-box-large').hide();
Run Code Online (Sandbox Code Playgroud)

但是有没有更好的选择器方法呢?IE8在这种向上遍历方面有什么特殊原因吗?

lon*_*day 5

最好的使用方法是closest,它找到与选择器匹配的最接近的祖先元素:

$this.closest('div.box-1').hide();
Run Code Online (Sandbox Code Playgroud)