我正在使用div的仪表板,每个div都有一个按钮所在的树。每次我必须知道那个div的ID是多少时,我都会大量使用parent()。

通常,我正在执行$(this).parent().parent().parent()来查找div的ID,因此可以为其设置变量。该应用程序基于每个div的ID。

是否认为使用parent()最多3次会很慢,但在每个函数上使用率却很高?

还有其他选择吗?

我正在寻找类似基准的东西,它可以显示出更快的结果。

这是树的示例:

<div id="6179827893" class="dashdiv">
   <div class="buttons">
     <li><a href="#" class="btn1">Button 1</a></li>
     <li><a href="#" class="btn2">Button 2</a></li>
     <li><a href="#" class="btn3">Button 3</a></li>
     <li><a href="#" class="btn4">Button 4</a></li>
     <li><a href="#" class="btn5">Button 5</a></li>
     <li><a href="#" class="btn6">Button 6</a></li>
   </div>
   <div class="dashcontent">

    ....

   </div>
</div>

最佳答案

您有几种选择可以达到相同的效果。

基准:http://jsperf.com/parents-method。根据此基准,我的方法比您的方法快大约100倍。

Method (see below) : Operations per second (higher is better)
parentNode3x       : 4447k
$(parentNode3x)    :  204K
$().closest        :   35k
$().parents        :    9k
$().parent()3x     :   44k

// Likely the fastest way, because no overhead of jQuery is involved.
var id = this.parentNode.parentNode.parentNode.id;

// Alternative methods to select the 3rd parent:
$(this.parentNode.parentNode.parentNode) // Native DOM, wrapped in jQuery

// Slowpokes
$(this).closest('.dashdiv')              // Hmm.
$(this).parents('.dashdiv:first')        // Hmm...

关于jquery - Parent(),更快的替代方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8789362/

10-10 08:40
查看更多