简体   繁体   English

使用jQuery选择列表中的第二和第三列表项

[英]selecting 2nd and 3rd list items in a list with jquery

I have a list. 我有一个清单。

<ul id="navigation">
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>

And using jquery id like to apply a clas to the 2nd and 3rd list items. 并使用jquery id像将clas应用于第二和第三列表项。

Is there simple code for me to do this? 我可以通过简单的代码来执行此操作吗?

Thanks 谢谢

最简单的方法是使用逗号分隔符将第二和第三列表项分组:

$("#navigation li:nth-child(2), #navigation li:nth-child(3)").addClass("name");
$("#navigation li:eq(1), #navigation li:eq(2)").addClass("someClass");

看看:eq选择器。

While Cletus is right, and the simplest thing you can do is use the standard jQuery comma-separated list, if it turns out you need to choose a whole lot of them, you should start looking at the .nextUntil() and .prevUntil() methods. 虽然Cletus是正确的,但是您可以做的最简单的事情就是使用标准的jQuery逗号分隔列表,如果事实证明您需要选择很多,则应该开始查看.nextUntil( .prevUntil( )方法。 You'd use them like so: 您将像这样使用它们:

$("#navigation li:nth-child(2)").nextUntil(":nth-child(4)").addClass("name");

试试吧

$("#navigation li:gt(0):lt(2)").addClass("t");

您正在寻找第n个子选择器。

$("ul li:nth-child(2)").addClass('MyClass');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM