问题
I have a table with more than 9 rows.
If I do this : $('table tr:gt(3):lt(6)'), shall I receive 3 or 6 elements at the end, and why? Are all selectors applied to the same primary selection, or are they successively applied on different selections?
回答1:
They're applied sequentially, so first you will filter away the first four elements (:gt(3)), then you will filter away all elements after the sixth (:lt(6)) element of the already filtered set.
Imagine this HTML:
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
<br/><br/>
Then do the following jQuery:
$('br:gt(3):lt(6)').addClass('sel');
You will now have:
<br/><br/>
<br/><br/>
<br class="sel"/><br class="sel"/>
<br class="sel"/><br class="sel"/>
<br class="sel"/><br class="sel"/>
<br/><br/>
回答2:
I suggest you use the slice() method instead.
http://docs.jquery.com/Traversing/slice#startend
$('table tr').slice(2, 5).addClass("something");
回答3:
Not quite what you might think-
Working Demo
Basically, the second filter is applied sequentially, to the matched set of the first filter.
For example, on a table with 10 rows, :gt(3) will filter to elements 5 - 10, then :lt(6) will be applied to the 6 elements, not filtering any.
if you add /edit to the demo URL, you can play with the selector and see for yourself. If you change the second filter to :lt(2), you get rows 5 and 6 highlighted in red
回答4:
For some reason :lt(6) will be ignored in that selection, so it will return everything greater than 3 in this intsance.
However, if you switch it over, it will work as expected
$('table tr:lt(6):gt(3)')
will return 2 rows (only row 4 and 5 is between 6 and 3).
**edit:**using v.1.3.2
And also, lt(6) isn't ignored, not just working as I expected it to. So :gt(3):lt(6) will in fact return 6 elements (if you have enough rows, that is)
来源:https://stackoverflow.com/questions/1137182/chaining-jquery-selectors-lt-and-gt