使用 jQuery 选择前“n”个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1865552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting the first "n" items with jQuery
提问by Omiod
With Jquery, I need to select just the first "n" items from the page, for example the first 20 links instead of selecting all of them with the usual
使用 Jquery,我只需要从页面中选择前“n”个项目,例如前 20 个链接,而不是用通常的方式选择所有链接
$("a")
Sounds simple but the jQuery manual has no evidence of something like this.
听起来很简单,但 jQuery 手册没有证据表明这样的事情。
回答by istruble
回答by kgiannakakis
Use lt pseudo selector:
使用 lt 伪选择器:
$("a:lt(n)")
This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.
这匹配第 n 个之前的元素(排除第 n 个元素)。编号从 0 开始。
回答by Arlind Nushi
I found this note in the end of the lt() docs:
我在lt() 文档的末尾找到了这个注释:
Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.
附加说明:
因为 :lt() 是 jQuery 扩展而不是 CSS 规范的一部分,所以使用 :lt() 的查询无法利用原生 DOM querySelectorAll() 方法提供的性能提升。为了在现代浏览器中获得更好的性能,请改用 $("your-pure-css-selector").slice(0, index) 。
So use $("selector").slice(from, to)
for better performances.
所以使用$("selector").slice(from, to)
以获得更好的性能。
回答by David Hellsing
Try the :lt selector: http://docs.jquery.com/Selectors/lt#index
试试 :lt 选择器:http: //docs.jquery.com/Selectors/lt#index
$('a:lt(20)');
回答by Kevin Gwynn
.slice() isn't always better. In my case, with jQuery 1.7 in Chrome 36, .slice(0, 20) failed with error:
.slice() 并不总是更好。就我而言,在 Chrome 36 中使用 jQuery 1.7,.slice(0, 20) 失败并出现错误:
RangeError: Maximum call stack size exceeded
RangeError:超出最大调用堆栈大小
I found that :lt(20) worked without error in this case. I had probably tens of thousands of matching elements.
我发现 :lt(20) 在这种情况下没有错误。我可能有数以万计的匹配元素。