总有人间一两风,填我十万八千梦

jQuery .:eq() Selector 用法 手册 | 示例代码

jQuery开发手册 归档 238℃ 0评论

描述: 在匹配的集合中选择索引值为index的元素。

  • 添加的版本: 1.0jQuery( “:eq(index)” )

    index: 要匹配元素的索引值(从0开始计数)

  • 添加的版本: 1.8jQuery( “:eq(-index)” )

    -index: 要匹配元素的索引值(从0开始计数), 从最后一个元素开始倒计数

这种索引值相关的选择器(:eq(), :lt(), :gt(), :even, :odd)过滤他们前面的匹配表达式的集合元素。进一步筛选的依据就是这个元素在原先匹配集合中的顺序。例如,如果第一个选择器使用类选择器( .myclass )进行匹配,四个元素返回,这些元素是给定索引是03

请注意,由于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)代替。

例子:

Example: 查找第三个 td。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.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>

Example: 在列表项目中应用三种不同的样式,以此来展示 :eq() 只会选择一个元素,而 :nth-child() 或 :eq() 会像 .each() 一样,有类似循环的构造,从而选择多个元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.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>

Example: Add a class to List 2, item 2 by targeting the second to last <li>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<style>
.foo {
color: blue;
background-color: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-latest.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>

转载请注明:悠然品鉴 » jQuery .:eq() Selector 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址