如何选择索引值在一定范围内的列表项?

我想将一个类分配给.index()列表的列表项,其中.index()值介于10到20之间。

如何使用jQuery选择这些元素?

 
  • One
  • Two
  • Three
  • ... ... ... ... li>Thirty

所以我想要类似的东西

 $('#id').click(function(){ //Assign class 'classname' to those li elements //between 10th and 20th (index numbers) in the list if([li element's index is between 10 and 20]).addClass('classname'); }); 

使用slice获取选择中元素的子集:

 $('li').slice(10, 20).addClass('classname'); 

虽然我建议使用lonesomeday的方法,但这里有一种纯粹使用选择器的方法:

 $("ul li:gt(8) + li:lt(10)").addClass('classname'); 

请注意,作为gtlt使用0的索引,如果你想要>= 10你需要使用8(大于9)。

例如: http : //jsfiddle.net/GybxF/21/

Altough lonesomeday的答案是正确的,可能更好。 这是一个不同的解决方案。

http://jsfiddle.net/E4U6Y/

HTH 🙂