gpt4 book ai didi

javascript - 选择器 : Fastest way to get descendants of a specific level only

转载 作者:行者123 更新时间:2023-11-28 20:17:51 25 4
gpt4 key购买 nike

我有一个像这样的表:

<table id="table">
<tbody>
<tr></tr>
<tr>
<td>
<table>
<tbody>
<tr></tr>
</tbod>
</table>
</td>
</tr>
</tbody>
</table>

我正在使用 jQuery,并且存在一个存储的选择器来获取最外层的表:

var x = $('#table')

从此开始如果想获得所有第一级<tr> -元素。

如果我使用其中之一:

x.find('tbody > tr');
x.children('tbody').children();

...第一个自然会选择所有嵌套的 <tr> - 元素也是如此。后者似乎过于复杂并且涉及多个查询。

有没有办法让它更快/更高效?

最佳答案

首先,x.find('tbody > tr')会找到所有<tr> s。你需要做x.find('> tbody > tr') ,假设xx从你的例子来看。

我对两者进行了测试,这是我的发现。

.children(): 3.013ms
>: 0.626ms

所以>方法比 .children() 更快方法。函数调用加起来……几乎没有。

这是我用于测试的 JavaScript。

var $table = $('#table'), $usingChildren, $usingAngleBracket;

console.time('.children()');
$usingChildren = $table.children('tbody').children('tr');
console.timeEnd('.children()');

console.time('>');
$usingAngleBracket = $table.find('> tbody > tr');
console.timeEnd('>');

console.log( $usingChildren, $usingAngleBracket );

关于javascript - 选择器 : Fastest way to get descendants of a specific level only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com