jQuery 选择器:获取子元素子集哪个更快?
$("tr td").slice(3, 6);
可能是这样的(从算法上来说,我的意思是;我知道为每个元素创建新的查询字符串有点愚蠢):
var subset = $( "tr td:nth-child(4)" );
for(var i=4; i<7; i++) subset.add( "tr td:nth-child("+i+")" );
哪个执行效率更高?还有其他更有效的解决方案吗?
Following up on this question, I have the following 2 options:
$("tr td").slice(3, 6);
And possibly something like this (algorithmically speaking, I mean; I know making new query strings for each element is kinda silly):
var subset = $( "tr td:nth-child(4)" );
for(var i=4; i<7; i++) subset.add( "tr td:nth-child("+i+")" );
Which would perform more efficiently? Would there be another more efficient solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个 (
$("tr td").slice(3, 6)
) 执行速度会快得多,因为它是单个选择器引擎调用,但一如既往,测试它!我设置了一个性能测试,以便您可以在这里亲自检查这两个(和其他答案):http://jsperf。 com/slice-性能测试
The first (
$("tr td").slice(3, 6)
) would perform much faster, as it's a single selector engine call, but as always, test it!I set up a performance test so you can check both (and other answers) yourself here: http://jsperf.com/slice-performance-test
在第一个代码中,您计算
$('tr td')
一次并获得一个切片。在第二个代码中,您计算
$('tr td')
4 次,然后每次提取第 4 到第 7 个子项。因此第一个代码更快。事实上,它也更容易阅读。
In the 1st code, you compute
$('tr td')
once and get a slice.In the 2nd code, you compute
$('tr td')
4 times, then extract the 4th to 7th child at each time.Therefore the 1st code is faster. In fact, it is easier to read as well.