Getting a range of elements in one jQuery selector

穿精又带淫゛_ 提交于 2019-12-18 05:43:20

问题


My problem is that I have a table, but I only want a subset of the rows, from first index to last index. I thought you could do it like this:

$('table tr:gt(2):lt(5)');

I thought it would give you only rows #3 and #4 but it ends up giving you more than that. How can I tell the selector to choose only rows #3 and #4?


回答1:


You're pretty close, but the problem in your selector is the :lt(5) filter.

You would want something like:

$('table tr:gt(2):lt(2)');

The difference is that by the time the lt() filter is applied, the first three elements were already removed from the set (by the gt() filter). So this will grab the 3rd and 4th element (zero-indexed), instead of the 3rd through the 8th.




回答2:


How about $('table tr').slice(2, 4)

Since JavaScript arrays are 0 indexed, that will give you the third and fourth row of the table. Slice will still return a jQuery wrapped (sub)set, so it's the same end result.




回答3:


I reckon you've got it spot on, although I would imagine that jQuery will count from 0 in it's index of elements.

So would it be gt(1) and lt(4) ?



来源:https://stackoverflow.com/questions/1954342/getting-a-range-of-elements-in-one-jquery-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!