通過 AJAX、append、html() 等動態添加的元素,原有事件綁定失效:
// 失效示例
$(".s-edited").hover(function() {
$(this).toggleClass("borderd");
});
// 動態添加後
$("#container").append('新元素'); // 無 hover 效果
| 方法 | 版本 | 狀態 | 說明 |
|---|---|---|---|
.live() | 1.3+ | ❌ 1.7 棄用,1.9 移除 | 綁定到 document,性能差、冒泡問題多 |
.delegate() | 1.4.2+ | ❌ 3.0 棄用 | 指定委托容器,優於 live |
.on() | 1.7+ | ✅ 現代標準 | 統一事件綁定 API,支持委托與直接綁定 |
// 語法:$(父容器).on(事件, 選擇器, 處理函數)
$("#container").on("hover", ".s-edited", function() {
$(this).toggleClass("borderd");
});
// 多事件綁定
$("#list").on("click mouseenter", ".item", handler);
// 數據傳遞
$("#list").on("click", ".item", {id: 123}, function(e) {
console.log(e.data.id);
});
#container).s-edited)this 指向真實目標元素document 或 body$(container).off("click", ".item") 防止內存洩漏data-id 替代 iddocument.getElementById("container").addEventListener("click", function(e) {
const target = e.target.closest(".s-edited");
if (target && this.contains(target)) {
target.classList.toggle("borderd");
}
});