[英]Best performance to select first 0 - n children of a parent in jQuery and javascript
I want to select the first n children under a specific parent. 我想选择特定父母下的前n个孩子。 For this case I don't want to use each index unless its the best performance.
对于这种情况,除非性能最佳,否则我不想使用每个索引。
Example: 例:
// select first 20 child elements
var twentyChildElements = $("div").children("span(20)");
<div>
<span index="1"/>
<span index="2"/>
<span index="3"/>
....
<span index="n"/>
</div>
You can use the :lt
pseudo-selector: 您可以使用
:lt
伪选择器:
var twentyChildElements = $("div > span:lt(20)");
>
means immediate children , and :lt(2)
means the first 20 elements that match the selector (it's zero-based, so this returns elements 0 through 19). >
表示直接子级 ,而:lt(2)
表示与选择器匹配的前20个元素(它是从零开始的,因此返回元素0到19)。
Just use jQuery's slice
: 只需使用jQuery的
slice
:
var twentyChildElements = $("div").children("span").slice(0, 20);
See also this performance test case - it's always faster than :lt(n)
, but can be outperformed by native selector engines. 另请参见此性能测试用例 -它总是比
:lt(n)
更快,但是可以被本机选择器引擎胜过。
您可以使用:lt
方法:
$("div").children("span:lt(n)")
Go fancy... Let css do the job! 看中...让CSS做这项工作! ;)
;)
Use a negative nth-child
combinator selector. 使用否定的
nth-child
组合选择器。 MDN nth-child selector MDN第n个子选择器
var twentyChildElements = $("div > span:nth-child(-n+20)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.