:nth-last-child()選擇器用於選擇所有屬於n的元素。th他們父母的最後一個孩子。元素的計數從最後一個元素開始。
用法:
:nth-last-child(n|even|odd|formula)
參數::nth-last-child()選擇器包含以下列出的參數:
- n:它保存所選元素的子索引號。計數從結束開始。第一個孩子的索引號是1。
- even:它選擇所有偶數子元素。
- odd:它選擇所有奇數子元素。
- formula:用於指定用於選擇子元素的公式。該公式可以采用(an + b)的形式。
以下示例說明了jQuery中的nth-last-child()選擇器:
範例1:本示例將其父母的倒數第二個標題(div標簽)的背景顏色更改為綠色,並將text-color更改為白色。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery |:nth-last-child() Selector
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to use nth-last-child selector -->
<script>
$(document).ready(function() {
$("h4:nth-last-child(2)").css({
"background-color":"green",
"color":"white"
});
});
</script>
<style>
option {
font-weight:bold;
font-size:25px;
color:green;
}
select {
font-weight:bold;
font-size:25px;
color:green;
}
</style>
</head>
<body style="text-align:center;">
<h1>
jQuery |:nth-last-child() Selector
</h1>
<div style= "border:1px solid blue;">
<h4>The first heading in first div.</h4>
<h4>The second last heading in first div.</h4>
<h4>The last heading in first div.</h4>
</div><br>
<div style= "border:1px solid blue;">
<h4>The first heading in second div.</h4>
<h4>The second last heading in first div.</h4>
<h4>The last heading in second div.</h4>
</div>
</body>
</html>
輸出:
範例2:本示例將<body>標簽的倒數第二個標題的背景顏色更改為綠色,並將text-color更改為白色。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery |:nth-last-child() Selector
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to use nth-last-child selector to
select nth last odd elements -->
<script>
$(document).ready(function() {
$("h4:nth-last-child(odd)").css({
"background-color":"green",
"color":"white"
});
});
</script>
<style>
option {
font-weight:bold;
font-size:25px;
color:green;
}
select {
font-weight:bold;
font-size:25px;
color:green;
}
</style>
</head>
<body style="text-align:center;">
<h1>
jQuery |:nth-last-child() Selector
</h1>
<div>
<h4>The first heading in body.</h4>
<h4>The second last heading in body.</h4>
<h4>The Third heading in body.</h4>
<h4>The Fourth heading in body.</h4>
</div>
</body>
</html>
輸出:
相關用法
- jQuery :even用法及代碼示例
- jQuery :first用法及代碼示例
- jQuery :odd用法及代碼示例
- jQuery :gt()用法及代碼示例
- jQuery :not()用法及代碼示例
- jQuery :last用法及代碼示例
- jQuery :lt()用法及代碼示例
- jQuery :contains()用法及代碼示例
- jQuery :header用法及代碼示例
- jQuery :parent用法及代碼示例
注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 jQuery | :nth-last-child() Selector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。