问题
How do I select the next "n" elements starting from the current element? What I mean is...
$(this).attr(...);
I want to do this "n" times. For the example of n=4:
$(this).attr(...);
$(this).next().attr(...);
$(this).next().next().attr(...);
$(this).next().next().next().attr(...);
or perhaps do it in a loop:
for (i = 0; i < n; i++) {
$(this).next().attr(...);
}
How can I do this? Is there a way I can do this by selecting the next "n" elements or in a loop?
回答1:
This should work:
$(this).nextAll().slice(0,4).attr(…)
Update:
This will work, too:
$(this).nextAll("*:lt(4)").attr(…)
回答2:
the nextAll method selects the following siblings of an element, optionally filtered by a selector. You could then follow that with a slice
to restrict to a smaller n.
回答3:
$(this).slice(start_index, end_index)
will select a portion of your selection. You could keep track of your current index in the loop and then apply the .slice(cur_index, cur_index+n)
function on the original set when you hit your condition.
来源:https://stackoverflow.com/questions/3461863/how-do-i-select-the-next-n-elements-starting-from-the-current-element-in-jquer