How do I select the next “n” elements starting from the current element in jQuery?

不打扰是莪最后的温柔 提交于 2020-07-17 06:07:30

问题


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

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