:eq(index)
在匹配的集合中选择索引值为index
的元素。
jQuery(":eq(index)")
index:要匹配元素的索引值(从0开始计数)
jQuery(":eq(-index)")
-index:要匹配元素的索引值(从0开始计数),从最后一个元素开始倒计数
这种索引值相关的选择器(:eq()
,:lt()
,:gt()
,:even
,:odd
)过滤他们前面的匹配表达式的集合元素。进一步筛选的依据就是这个元素在原先匹配集合中的顺序。例如,如果第一个选择器使用类选择器(.myclass
)进行匹配,四个元素返回,这些元素是给定索引是0
到3
。
请注意,由于JavaScript数组使用基于0的索引,这些选择器也是如此。这就是为什么$('.myclass:eq(1)')
选择器选择文档中第二个MyClass类的元素,而不是第一个。与此相反,:nth-child(n)
是基于1的索引的,以符合CSS规范。
在jQuery 1.8之前,:eq(index)
不接受负值所引值(虽然.eq(index)
方法接受)。
其他注意事项:
- 因为
:eq()
是一个 jQuery 延伸出来的选择器,并不是的CSS规范的一部分,使用:eq()
查询不能充分利用原生DOM提供的querySelectorAll()
方法来提高性能。为了在现代浏览器上获得更佳的性能,请使用$("your-pure-css-selector").eq(index)
代替。
例子
查找第三个 td。
<!DOCTYPE html> <html> <head> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <table border="1"> <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr> <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr> <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr> </table> <script>$("td:eq(2)").css("color", "red");</script> </body> </html>
在列表项目中应用三种不同的样式,以此来展示:eq()只会选择一个元素,而:nth-child()或:eq()会像.each()一样,有类似循环的构造,从而选择多个元素。
<!DOCTYPE html> <html> <head> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <ul class="nav"> <li>List 1, item 1</li> <li>List 1, item 2</li> <li>List 1, item 3</li> </ul> <ul class="nav"> <li>List 2, item 1</li> <li>List 2, item 2</li> <li>List 2, item 3</li> </ul> <script> /* applies yellow background color to a single <li> */ $("ul.nav li:eq(1)").css( "backgroundColor", "#ff0" ); /* applies italics to text of the second <li> within each <ul class="nav"> */ $("ul.nav").each(function (index) { $(this ).find("li:eq(1)").css( "fontStyle", "italic" ); }); /* applies red text color to descendants of <ul class="nav"> */ /* for each <li> that is the second child of its parent */ $("ul.nav li:nth-child(2)").css( "color", "red" ); </script> </body> </html>
Add a class to List 2, item 2 by targeting the second to last <li>
<!DOCTYPE html> <html> <head> <style> .foo { color: blue; background-color: yellow; } </style> <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script> </head> <body> <ul class="nav"> <li>List 1, item 1</li> <li>List 1, item 2</li> <li>List 1, item 3</li> </ul> <ul class="nav"> <li>List 2, item 1</li> <li>List 2, item 2</li> <li>List 2, item 3</li> </ul> <script> $( "li:eq(-2)" ).addClass( "foo" ) </script> </body> </html>