:nth-last-of-type() 選擇器


nth-last-of-type 選擇器

說明:選取與父項同類型同名的子項,從最後一個元素開始往第一個元素計算,第 n 個子項。

  • 新增版本:1.9jQuery( ":nth-last-of-type(index/even/odd/equation)" )

    index:要符合的每個子項的索引,從最後一個開始(1),字串 evenodd,或等式(例如 :nth-last-of-type(even):nth-last-of-type(4n)

由於 jQuery 實作 :nth- 選擇器是嚴格根據 CSS 規格,因此 n 的值是「1 開頭」,表示從 1 開始計算。對於其他選擇器表達式,例如 .first().eq(),jQuery 遵循 JavaScript 的「0 開頭」計算。假設有一個包含三個 <li><ul>$('li:nth-last-of-type(1)') 會選取第三個,也就是最後一個 <li>

可以在 W3C CSS 規格 中找到此用法的進一步說明。

範例

找到每個相符的 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
44
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-last-of-type demo</title>
<style>
div {
float: left;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.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-of-type(2)" ).append( "<span> - 2nd to last!</span>" );
</script>
</body>
</html>

示範

這是一個遊樂場,用來查看選擇器如何與不同的字串搭配使用。

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
80
81
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-last-of-type 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.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div>
<button>:nth-last-of-type(even)</button>
<button>:nth-last-of-type(odd)</button>
<button>:nth-last-of-type(3n)</button>
<button>:nth-last-of-type(2)</button>
</div>
<div>
<button>:nth-last-of-type(3n+1)</button>
<button>:nth-last-of-type(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>

示範