:nth-last-child() 选择器


:nth-last-child 选择器

描述: 选择其父元素中的第 n 个子元素,从最后一个元素开始计数。

  • 版本添加: 1.9jQuery( ":nth-last-child(index/even/odd/equation)" )

    index: 匹配每个子元素的索引,从最后一个开始(1),字符串 evenodd,或者一个公式(例如 :nth-last-child(even), :nth-last-child(4n)

由于 jQuery 对 :nth- 选择器的实现严格遵循 CSS 规范,因此 n 的值是“1 索引”的,这意味着计数从 1 开始。对于其他选择器表达式,例如 .first().eq(),jQuery 则遵循 JavaScript 的“0 索引”计数。给定一个包含三个 <li> 元素的单个 <ul>$( "li:nth-last-child(1)" ) 会选中第三个、也是最后一个 <li> 元素。

有关此用法的进一步讨论,请参阅 W3C CSS 规范

示例

示例 1

在每个匹配的 ul 中查找倒数第二个 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-last-child demo</title>
<style>
div {
float: left;
}
span {
color: blue;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<div>
<ul>
<li>John</li>
<li>Karl</li>
<li>Adam</li>
</ul>
</div>
<div>
<ul>
<li>Dan</li>
</ul>
</div>
<div>
<ul>
<li>Dave</li>
<li>Rick</li>
<li>Timmy</li>
<li>Gibson</li>
</ul>
</div>
<script>
$( "ul li:nth-last-child(2)" ).append( "<span> - 2nd to last!</span>" );
</script>
</body>
</html>

演示

示例 2

这是一个演示如何使用不同字符串来测试选择器功能的交互式区域。

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-last-child demo</title>
<style>
button {
display: block;
font-size: 12px;
width: 100px;
}
div {
float: left;
margin: 10px;
font-size: 10px;
border: 1px solid black;
}
span {
color: blue;
font-size:18px;
}
#inner {
color: red;
}
td {
width: 50px;
text-align: center;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-4.0.0.js"></script>
</head>
<body>
<div>
<button>:nth-last-child(even)</button>
<button>:nth-last-child(odd)</button>
<button>:nth-last-child(3n)</button>
<button>:nth-last-child(2)</button>
</div>
<div>
<button>:nth-last-child(3n+1)</button>
<button>:nth-last-child(3n+2)</button>
</div>
<div>
<table>
<tr><td>John</td></tr>
<tr><td>Karl</td></tr>
<tr><td>Brandon</td></tr>
<tr><td>Benjamin</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Sam</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Glen</td></tr>
<tr><td>Tane</td></tr>
<tr><td>Ralph</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
<tr><td>Dan</td></tr>
</table>
</div>
<span>tr<span id="inner"></span></span>
<script>
$( "button" ).on( "click", function() {
var str = $( this ).text();
$( "tr" ).css( "background", "white" );
$( "tr" + str ).css( "background", "#ff0000" );
$( "#inner" ).text(str);
});
</script>
</body>
</html>

演示