例子
查找第三个 td。
TD #0 | TD #1 | TD #2 |
TD #3 | TD #4 | TD #5 |
TD #6 | TD #7 | TD #8 |
$("td:eq(2)").css("color", "red");
在列表项目中应用三种不同的样式,以此来展示:eq()只会选择一个元素,而:nth-child()或:eq()会像.each()一样,有类似循环的构造,从而选择多个元素。
/* applies yellow background color to a single
*/$("ul.nav li:eq(1)").css( "backgroundColor", "#ff0" );
/* applies italics to text of the second
within each$("ul.nav").each(function(index) {
$(this).find("li:eq(1)").css( "fontStyle", "italic" );
});
/* applies red text color to descendants of
/* for each
that is the second child of its parent */$("ul.nav li:nth-child(2)").css( "color", "red" );
Add a class to List 2, item 2 by targeting the second to last
.foo {
color: blue;
background-color: yellow;
}
$( "li:eq(-2)" ).addClass( "foo" )