這一單元說明 jQuery 如何新增、刪除、包裝節點,以及如何在同一份文件裡有效率地尋找目標元素。
這兩個方法常被搞混:empty() 只清空內容,元素本身還在;remove() 則是把元素整個移出文件。
<p>Test Paragraph.</p>
<a href="#">jQuery</a>
function jq() {
$("p").wrap("<div class='wrap'</div>");
}
執行後等同於 <div class='wrap'><p>Test Paragraph.</p></div>。
function jq() {
$("p").wrap(document.getElementById('content'));
}
結果是 <div id="content"><p>Test Paragraph.</p></div>。
<p>Hello</p>
<p><span>Hello Again</span></p>
function jq() {
var f = $("p").add("span");
for (var i = 0; i < $(f).size(); i++) {
alert($(f).eq(i).html());
}
}
$("p") 選到兩個段落,加上 add("span") 後共三個元素,分別是 [<p>Hello</p>]、[<p><span>Hello Again</span></p>] 與 [<span>Hello Again</span>]。
$("p").add(document.getElementById("a"));
var f = $("p").add([document.getElementById("a"),
document.getElementById("b")]);
// 注意 els 是陣列,中括號不能省
<div>
<p>one</p>
<span><u>two</u></span>
</div>
function jq() {
var f = $("u").ancestors();
for (var i = 0; i < $(f).size(); i++) {
alert($(f).eq(i).html());
}
}
第一個元素以 <u> 的父節點內容為對象,得到 [<u>two</u>];第二個則再往上一層(div),得到 [<p>one</p><span><u>two</u></span>]。文件通常還有 body 與 html,可類推下去。
加上表達式即可過濾:改成 $("u").ancestors("div"),就只回傳 div 那一層。
<div id="ch">
<span>two</span>
<span id="sp">three</span>
</div>
alert($("#ch").children().html()); // 第一個子節點的內容
alert($("#ch").children("#sp").html()); // 過濾後得到 "three"
parent() 與 parent(expr) 取父節點,概念與 children 相反。
<p>This is just a test.</p>
<p>So is this</p>
alert($("p").contains("test").html());
$("p") 有兩個元素,只有第一個含 "test",因此回傳 [<p>This is just a test.</p>]。
結束目前的鏈式操作,回到前一次操作的狀態。這是鏈式搜尋能維持可讀性的關鍵。
<p>Hello</p>
<p>Hello Again</p>
<p class="selected">And Again</p>
alert($("p").filter(".selected").html());
從三個段落中只留下 class 為 selected 的那一個。
alert($("p").find("#a").html()); // 在 p 元素中繼續找 id 為 a 的節點
alert($("#a").is("p")); // 回傳 boolean
<p>Hello</p>
<p id="a">Hello Again</p>
<p class="selected">And Again</p>
alert($("p").next().html());
alert($("p").next(".selected").html());
next() 回傳 [<p id="a">Hello Again</p>, <p class="selected">And Again</p>];加上過濾條件後只剩一個。prev() 方向相反。
alert($("p").not(document.getElementById("a")).html());
alert($("p").not("#a").html());
從集合中排除特定元素,結果為 [<p>one</p>]。
<p>one</p>
<div><p id="a">two</p></div>
alert($("div").siblings().eq(1).html());
alert($("div").siblings("a").html());
這些方法可以串起來使用,形成清楚的搜尋鏈:$("div").find("p").filter(".active").next().addClass("highlight")。與其反覆用 $() 從文件根節點重新搜尋,善用 these 相對定位方法能讓程式碼更快也更省資源。