jQuery 的插入方法幾乎都是成對出現的:append() 對應 appendTo()、insertBefore() 對應 before()。理解這組「反向方法」的關係,寫 DOM 操作時就能少繞很多彎。
先看一段常見的寫法:我們先建立一段內容並插入到某個元素前面,接著又想把「同一個元素」插到文件中的另一個位置。理想上我們希望用鏈式(chaining)一次寫完,但這裡做不到——因為 this 在 insertBefore() 中是「目標」,在 appendTo() 中卻是「被插入的內容」,兩者的主詞剛好相反,鏈不起來。
反向插入方法就是為了解這個尷尬。它們執行的是同一件事,只是把「目標」與「內容」對調。例如下面兩行程式碼效果完全相同:
$('<p>Hello</p>').appendTo('#container');
$('#container').append('<p>Hello</p>');
把 insertBefore() 換成 before(),鏈式就能重新接回來。以下片段為每個 span.footnote 建立上標編號,並把腳注收集到一個 <ol id="notes"> 清單裡:
$(document).ready(function() {
var $notes = $('<ol id="notes"></ol>').insertBefore('#footer');
$('span.footnote').each(function(index) {
$(this)
.before('<sup>' + (index + 1) + '</sup>')
.appendTo($notes)
.wrap('<li></li>');
});
});
反向插入方法和 .attr()、.css() 一樣,可以傳入函式作為參數,該函式會對每個目標元素各呼叫一次,回傳要插入的 HTML 字串。不過在這個例子裡,每個腳注要做的動作是一整串而非單一插入,因此用一個 .each() 包住反而更清楚。
接下來要替每個腳注建立雙向連結:正文裡要有指向腳注的錨點,腳注裡也要有回到正文的連結。每個腳注因此至少需要四處標記(兩個連結、兩個 id),字串拼接的複雜度瞬間上升。
用 + 相加當然可行,但片段一多可讀性就變差。改用陣列的 join() 會整齊得多,兩種寫法結果相同:
var str = 'a' + 'b' + 'c';
var str = ['a', 'b', 'c'].join('');
雖然 join() 要多打幾個字元,卻能避免混亂。另外要注意:陣列元素是各自獨立求值的,所以 index + 1 不必再加括號。
$(document).ready(function() {
var $notes = $('<ol id="notes"></ol>').insertBefore('#footer');
$('span.footnote').each(function(index) {
$(this)
.before([
'<a href="#footnote-', index + 1,
'" id="context-', index + 1,
'" class="context">',
'<sup>', index + 1,
'</sup></a>'
].join(''))
.appendTo($notes)
.wrap('<li></li>');
});
});
接著替清單項目補上配對的 id,並用 append()(也就是 appendTo() 的反向方法)在腳注後方加上回到正文的連結:
$(document).ready(function() {
var $notes = $('<ol id="notes"></ol>').insertBefore('#footer');
$('span.footnote').each(function(index) {
$(this)
.before([
'<a href="#footnote-', index + 1,
'" id="context-', index + 1,
'" class="context">',
'<sup>', index + 1,
'</sup></a>'
].join(''))
.appendTo($notes)
.append([
' (<a href="#context-', index + 1,
'">context</a>)'
].join(''))
.wrap('<li id="footnote-' + (index + 1) + '"></li>');
});
});
這裡 href 指向的是腳注標籤上剛建立的 id,兩端因此形成完整的雙向跳轉。執行後可以看到每個腳注都帶上了新連結。