javascript 如何使用 jQuery .next() 选择接下来的 2 个(或超过 2 个)项目?

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

How to select next 2 (or more than 2) items using jQuery .next()?

javascriptjqueryjquery-selectors

提问by Jitendra Vyas

using jQuery's .nextfunction I want to show next 2 items. By default it selects only just next item.

使用 jQuery 的.next功能,我想显示下 2 个项目。默认情况下,它只选择下一个项目。

I need control, like sometimes I need next 2, sometime next 3

我需要控制,就像有时我需要下 2 个,有时需要下 3 个

回答by Nick Craver

You can use .nextAll()and a :lt()selector, for example:

您可以使用.nextAll():lt()选择器,例如:

.nextAll(':lt(2)') //next 2
.nextAll(':lt(3)') //next 3

Try it out here. If you need it to be programmatic (instead of string concatenation) and change it easily, use .slice()instead:

在这里尝试一下。如果您需要它是程序化的(而不是字符串连接)并轻松更改它,请.slice()改用:

.nextAll().slice(0, 2) //next 2
.nextAll().slice(0, 3) //next 3

This method allows you to pass as a parameter the number you need a bit easier. You can test it here.

此方法允许您将需要的数字作为参数更容易地传递。 你可以在这里测试它

回答by ScottyG

If you want to select the next number of elements and include the selected element you can do something like:

如果要选择下一个元素数量并包含所选元素,您可以执行以下操作:

$('div#myTarget').nextAll('div').andSelf().slice(0,4)

The above code returns the next 4 div elements after the div myTarget and includes the myTarget div itself.

上面的代码返回 div myTarget 之后的接下来的 4 个 div 元素,并包括 myTarget div 本身。

.slice(0,4)selected the next 4 elements and .andSelf()included the original selected element

.slice(0,4)选择了接下来的 4 个元素并.andSelf()包含了原始选择的元素

回答by hobbs

Use .nextAllinstead of .nextto get all following siblings, and then use .sliceto narrow that down to a range.

使用.nextAll而不是.next获取所有后续兄弟姐妹,然后使用.slice将其缩小到一个范围。