<p>I would like to say: </p>
// 正常:完整 HTML 片段
$('p').append('<b>Hello</b>');
// 結果: <p>I would like to say: <b>Hello</b></p> ✅
// 陷阱:分兩次追加
$('p').append('<b>');
$('p').append('Hello</b>');
// 結果: <p>I would like to say: <b></b>Hello</p> ❌
append() 內部使用 DOMParser 或 innerHTML 解析傳入字串。瀏覽器解析器遇到 <b> 這類未閉合標籤時,會自動補全閉合標籤以維持 DOM 樹合法。第二次追加時,Hello</b> 已經是文字節點,不再被視為標籤內容。
var html = '<b>Hello</b>';
$('p').append(html);
var $b = $('<b>').text('Hello');
$('p').append($b);
var frag = document.createDocumentFragment();
var b = document.createElement('b');
b.textContent = 'Hello';
frag.appendChild(b);
$('p')[0].appendChild(frag);
var items = ['Apple', 'Banana', 'Orange'];
var html = '';
$.each(items, function(i, fruit) {
html += '<li>' + fruit + '</li>';
});
$('#list').append(html); // 單次 DOM 操作
.prepend().after().before().html().replaceWith()// 簡化版 jQuery append 邏輯
function append(content) {
return this.each(function() {
// 1. 統一轉為 DOM 節點陣列
var nodes = typeof content === 'string'
? jQuery.parseHTML(content) // 這裡會自動閉合標籤
: [content];
// 2. 追加到當前元素
nodes.forEach(function(node) {
this.appendChild(node);
}, this);
});
}
append() 不是字串拼接器,而是 DOM 片段插入器。瀏覽器解析器會自動修補不完整 HTML,導致分段追加標籤失效。養成「完整片段一次插入」或「建構元素後插入」的習慣,避開此坑。