本篇聚焦於 jQuery 的子元素過濾選擇器,透過範例來理解:nth-child、:first-child、:last-child 與:only-child 的用法。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery-1.3.2.js"></script>
<script type="text/javascript"><!--
$(function(){
$("#aNth1").click(function(){ $("#ul1 li:nth-child(even)").each(function(){ $(this).css("background","#773300"); }) })
$("#aNth2").click(function(){ $("#ul1 li:nth-child(2n+1)").each(function(){ $(this).css("background","#ff3434"); }) })
$("#aFirst").click(function(){ $("#ul1 li:first-child").each(function(){ $(this).css("background","#223344"); }) })
$("#aLast").click(function(){ $("#ul1 li:last-child").each(function(){ $(this).css("background","#99ff88"); }) })
$("#aOnly").click(function(){ $("ul li:only-child").each(function(){ $(this).css("background","#99ff88"); }) })
})
// --></script>
<title>無標題文檔</title>
</head>
<body>
<a href="#" onclick="javascript:location.reload();">重置</a>
<ul id="ul1">
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
<li>li6</li>
</ul>
<ul>
<li>li7</li>
</ul>
<a href="#" id="aNth1">設置 ul1 的偶索引子元素的背景顏色</a>|
<a href="#" id="aNth2">設置 ul1 的奇索引子元素的背景顏色</a>|
<a href="#" id="aFirst">設置 ul1 的頭子元素的背景顏色</a>|
<a href="#" id="aLast">設置 ul1 的尾子元素的背景顏色</a>|
<a href="#" id="aOnly">設置所有 ul 中唯一子元素的背景顏色</a>
</body>
</html>
1. $("ParentSelector ChildTagName:nth-child(...)")(以下簡寫為 :nth-child)
對父選擇器所選元素的子元素進行索引篩選。例如點擊 aNth1 後,會以 $("#ul1 li:nth-child(even)") 選取 ID 為 ul1 的 li 子元素中的偶索引項。要注意的是,此處的索引從 1 開始(與第三章的 :even/:odd 從 0 起算不同)。此外也可寫成 nth-child(2n+1) 來達到選取奇數項的效果,或直接指定具體索引(如 "2"),但同樣記得索引從 1 起算。
返回值:Array(Element)。
2. :first-child
取得所選元素集合中的頭元素。
返回值:Array(Element)。
3. :last-child
取得所選元素集合中的尾元素。
返回值:Array(Element)。
4. :only-child
取得沒有兄弟節點的元素。例如範例中第二個 ul 只有一個 li 子元素,因此 $("ul li:only-child") 只會選到 li7。
返回值:Array(Element)。