父(),更快的选择? [英] Parent(), faster alternative?

查看:94
本文介绍了父(),更快的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用div的仪表板,每个div都有一个按钮所在的树。每次我都必须知道该div的id是什么,所以我使用parent()很多。



大部分我在做 $(this).parent()。parent()。parent()来寻找div的ID,所以我可以设置变量。该应用程序基于每个div的id。



使用parent()可以使用3次,但几乎可以使用每个函数吗?



是否有其他选择?



我正在寻找类似基准样式的东西,

以下是树的示例:

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

....

< / div>
< / div>


解决方案

效果。



基准: http://jsperf.com/parents-method。根据这个基准,我的方法比你的方法快100倍。

 方法(见下文):每秒操作)
parentNode3x:4447k
$(parentNode3x):204K
$()。closest:35k
$()。parents:9k
$()。 parent()3x:44k

//可能是最快的方法,因为不涉及jQuery的开销。
var id = this.parentNode.parentNode.parentNode.id;

//选择第三个父项的另一种方法:
$(this.parentNode.parentNode.parentNode)//包装在jQuery中的Native DOM

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


I am working with a dashboard of divs and each div it has a tree of which the buttons are. Every time I have to know which the id of that div is so I am using parent() alot.

Mostly I am doing $(this).parent().parent().parent() to find the ID of div so I can set variables to it. The app is based on the id's of each div.

Is it consider slow to use parent() up to 3 times but pretty much on every function?

Is there any other alternative?

I am looking for something like benchmarks-style which shows what's faster.

Here is an example of the tree:

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

解决方案

You've got a few options to achieve the same effect.

Benchmark: http://jsperf.com/parents-method. According to this benchmark, my method is roughly 100x faster than your method.

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...

这篇关于父(),更快的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆