DIV CSS 佈局教程網

jQuery 學習筆記:選擇器之二(層級選擇器)
編輯:JQuery特效代碼     

本篇說明 jQuery 的層級選擇器,用來選取某節點的子孫、直屬子、後續兄弟與同級兄弟等關係節點。

<!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" />
<title>無標題文檔</title>
<script src="js/jquery-1.3.2.js" ></script>
<script type="text/javascript"><!--
$(function(){
$("#aDescendant").click(function(){ $("#Result").html(""); $("#div1 ul").each(function(){ $("#Result").html($("#Result").html() + $(this).html() + "," ); }) })
$("#aChild").click(function(){ $("#Result").html(""); $("#div1 > li").each(function(){ $("#Result").html($("#Result").html() + $(this).attr("id") + "," ); }) })
$("#aNext").click(function(){ $("#Result").html(""); $("label + input").each(function(){ $("#Result").html($("#Result").html() + $(this).attr("value") + ","); }) })
$("#aSibling").click(function(){ $("#Result").html(""); $("#input1 ~ label").each(function(){ $("#Result").html($("#Result").html() + $(this).html() + ","); }) })
})
// --></script>
</head>
<body>
<div id="div1">
<li id="l1">
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
<ul>4</ul>
</li>
<li id="l2">
<ul>一</ul>
<ul>二</ul>
<ul>三</ul>
<ul>四</ul>
</li>
<label>Label1</label>
<input id="input1" value="input1" />
<input />
<label>Label2</label>
<label>Label4</label>
</div>
<div>
<label>Label3</label>
<div style="border:1px solid #000" ></div>
<input id="input2" value="input2"/>
</div>
<label>Label4</label><br />
<a href="#" id="aDescendant">顯示 DIV 的後序結點 ID</a>
<a href="#" id="aChild">顯示 DIV 的子 LI 結點</a>
<a href="#" id="aNext">顯示位於 Label 下一個 input 元素的 value 值</a>
<a href="#" id="aSibling">顯示於 input1 元素同級的 label 元素內容</a>
<br />
Result:
<div id="Result"></div>
</body>
</html>

先補充一個課外知識點

element.attr("attributeName")
用於取得某 element 元素的指定屬性值,例如 $("#div1 > li").each(function(){ ... $(this).attr("id") ... }) 會取得當前遍歷到的 element 的 id 值。

層級選擇器說明

1. $("Selector descendant")
取得「Selector」所選元素的子孫節點。例如 $("#div1 ul") 會取得 id 為 div1 元素的子孫節點中所有 ul 節點的 HTML 內容。若 Selector 回傳的是集合,則會取得該集合中每個元素相符的子孫節點集合。
返回值:Array(Element)。

2. $("Selector>child")
與上一個類似,主要差別在於只取得「直屬」的子節點(多個 > 即代表直屬關係),而非全部子孫節點。
返回值:Array(Element)。

3. $("Selector + next")
取得緊接在 Selector 之後的 next 元素。例如 $("label + input") 會取得緊跟在 label 後面的 input。範例中只有 input1 緊接 Label1,而 input2 與 Label3 之間隔了 div,故不符合。
返回值:Array(Element)。

4. $("Selector ~ Sibling")
與上一個類似,差別在於此選擇器匹配的是位於 Selector 之後的所有同級 Sibling 節點,不論中間是否隔著其他節點。
返回值:Array(Element)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved