為動態添加的元素綁定事件,利用事件冒泡機制在文檔根節點委託處理。注意:jQuery 1.7+ 已棄用,1.9+ 移除。
document 根節點$(event.target).closest(selector)
// 綁定
$('.clickme').live('click', function() {
alert('Live handler called.');
});
// 動態添加元素
$('body').append('Another target');
// 新元素自動生效,無需重新綁定
$('.parent').find('.child').live(...) 無效,必須直接選擇器 $('.child').live(...)event.stopPropagation() 無法阻止委託,必須返回 false
// 推薦:文檔委託 (最接近 .live() 行為)
$(document).on('click', '.clickme', function() {
alert('Delegated handler');
});
// 更佳:就近父容器委託 (性能更優)
$('#container').on('click', '.clickme', function() {
alert('Optimized delegation');
});
// 多事件綁定
$('#container').on({
click: function() { ... },
mouseenter: function() { ... },
mouseleave: function() { ... }
}, '.clickme');
| .live() 寫法 | .on() 替代寫法 |
|---|---|
$(sel).live(event, fn) | $(document).on(event, sel, fn) |
$(sel).die(event, fn) | $(document).off(event, sel, fn) |
$(sel).live({events}) | $(document).on({events}, sel) |
document.off() 防止內存洩漏.on('click.myPlugin', ...) 便於精確解綁