prepend() 方法向每個匹配元素內部開頭插入內容,是 append() 的鏡像操作。同樣支持多參數混合傳入,適用於日誌倒序顯示、通知列表新增置頂、表單驗證錯誤提示前置等場景。
$(selector).prepend(content1, content2, ...);
// 參數類型同 append():HTML字符串、jQuery對象、DOM元素、文本節點
兩個按鈕分別為段落前置文本、為有序列表前置列表項:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>
</body>
</html>
<!-- 點擊 "Prepend text" 後 -->
<p><b>Prepended text</b>. This is a paragraph.</p>
<p><b>Prepended text</b>. This is another paragraph.</p>
<!-- 點擊 "Prepend list item" 後 -->
<ol>
<li>Prepended item</li>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
| 場景 | 推薦方法 | 原因 |
|---|---|---|
| 固定容器,動態內容 | prepend() | 語義清晰,鏈式調用 |
| 固定內容,多目標容器 | prependTo() | 返回新元素便於後續操作 |
| 需獲取插入元素引用 | prependTo() | 直接返回 jQuery 對象 |
function prependItems(container, items) {
const frag = document.createDocumentFragment();
items.reverse().forEach(item => { // 反轉順序保證最終順序正確
frag.insertBefore(createEl(item), frag.firstChild);
});
$(container).prepend(frag);
}
prepend() 保持最新在頂$input.before($("").text(msg))掌握 prepend() 與其家族方法的異同,能讓動態 DOM 構建更得心應手。