在動態網頁中,元素可能在頁面載入後才被創建。若直接對尚不存在的元素綁定事件(後綁定),新元素將無法響應。jQuery 提供 .live()、.delegate()、.on() 實現「前綁定」(事件委派),讓動態元素自動擁有事件處理能力。本文透過實例詳細比較兩者差異與最佳實踐。
| 類型 | 說明 | 代表方法 |
|---|---|---|
| 後綁定 | 直接針對現有元素綁定,動態新增元素無效 | .click(), .bind() |
| 前綁定(委派) | 綁定在祖先元素,利用事件冒泡捕獲動態子元素事件 | .delegate(), .live(), .on() |
<div id="main">
<a href="#">既有連結 1</a><br>
<a href="#">既有連結 2</a><br>
</div>
<button id="btnCreate">動態新增連結</button>
<script>
$(function() {
// 1. 後綁定:動態新增的 a 無效
// $("#main > a").click(function(){ alert($(this).text()); });
// 2. 前綁定 delegate(推薦,jQuery 1.4.2+)
// $("#main").delegate("a", "click", function(){ alert($(this).text()); });
// 3. 前綁定 live(已棄用,jQuery 1.7+ 移除)
// $("#main a").live("click", function(){ alert($(this).text()); });
// 4. 現代寫法 on(jQuery 1.7+ 推薦)
$("#main").on("click", "a", function() {
alert($(this).text());
});
// 動態新增
$("#btnCreate").click(function() {
$("
我是動態創建的").appendTo("#main");
});
});
</script>
document,所有事件冒泡到頂層才處理,效能最差。#main),冒泡路徑較短,效能較好。$(ancestor).on(event, selector, handler),效能與 .delegate() 相同,為目前標準寫法。.on(),指定最近的靜態祖先元素。document 或 body 上大量委派。$(selector).on("click", handler) 更簡潔。.off("click", "a")。stopPropagation() 阻擋會導致委派失效。iframe 或 Shadow DOM 內,需在對應文檔上綁定。.live() 不支援鏈式呼叫與 event.stopImmediatePropagation()。