使用 jQuery 选择最后 5 个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1948152/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:26:59  来源:igfitidea点击:

Select last 5 elements with jQuery

jquerycss-selectors

提问by Adam

Is it possible to select the last 5 child divs of an element?

是否可以选择元素的最后 5 个子 div?

回答by Guffa

Yes, you can get the div elements, and then use the slicemethod to get the last five:

是的,你可以获取div元素,然后使用该slice方法获取最后五个:

var e = $('#someelement > div').slice(-5);

回答by Sampson

Sure, you could use the .lengthproperty of a selector to get the count, and then use the :gt(n)selector to get the last 5.

当然,您可以使用.length选择器的属性获取计数,然后使用:gt(n)选择器获取最后 5 个。

var o = $("div.container > div:gt("+($("div.container > div").length-5)+")");

回答by Gone Coding

As of jQuery 1.8, you can use a negative value in the :gt()pseudo selector.

从 jQuery 1.8 开始,您可以在:gt()伪选择器中使用负值。

Reference: https://api.jquery.com/gt-selector.

参考:https: //api.jquery.com/gt-selector

e.g.

例如

var e = $('#someelement > div:gt(-6)');

JSFiddle:https://jsfiddle.net/TrueBlueAussie/g4drety2/3/

JSFiddle:https ://jsfiddle.net/TrueBlueAussie/g4drety2/3/

Notes:

笔记:

  • The value needs to be n+1
  • .slice(-5)is faster as :gtcannot use browser performance boosting.
  • 值必须是 n+1
  • .slice(-5)速度更快,因为:gt不能使用浏览器性能提升。