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

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

问题描述

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

大多数情况下,我正在执行 $(this).parent().parent().parent() 来查找 div 的 ID,以便我可以为其设置变量.该应用程序基于每个 div 的 ID.

使用 parent() 最多 3 次,但几乎在每个函数上都使用会很慢吗?

还有其他选择吗?

我正在寻找类似基准测试风格的东西,它可以显示更快的速度.

这是树的一个例​​子:

<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 class="dashcontent">....

解决方案

您有几个选项可以达到相同的效果.

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

Method(见下文):每秒操作数(越高越好)parentNode3x:4447k$(parentNode3x):204K$().closest : 35k$().父母:9k$().parent()3x : 44k//可能是最快的方式,因为不涉及 jQuery 的开销.var id = this.parentNode.parentNode.parentNode.id;//选择第三个父级的替代方法:$(this.parentNode.parentNode.parentNode)//原生 DOM,包裹在 jQuery 中//慢波$(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...

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆