jQuery 1.7+ 推出 .on() 統一替代 .bind()、.live()、.delegate(),是現代 jQuery 事件處理核心。
// 1. 直接綁定 (等同舊 .bind())
$(selector).on(events, handler);
// 2. 事件委託 (等同舊 .delegate())
$(ancestor).on(events, selector, handler);
// 3. 多事件對象綁定
$(selector).on({
click: handler1,
mouseenter: handler2,
mouseleave: handler3
});
// 4. 傳遞數據
$(selector).on(event, data, handler);
// handler 中通过 event.data 訪問
// 5. 命名空間
$(selector).on('click.myPlugin', handler);
// 精確解綁
$(selector).off('click.myPlugin');
;(function($) {
$.fn.hello = function(options) {
const opts = $.extend({ size: 0 }, options);
const handlers = {
play(opts) {
this.autoPlay();
this.bindEvents();
},
autoPlay() { console.log('auto'); },
bindEvents() {
const $target = $('#test');
// 多事件對象綁定 (推薦)
$target.on({
click() { alert('click'); },
mouseenter() { alert('enter'); },
mouseleave() { alert('leave'); }
});
/*
// 單事件委託 + 數據傳遞 (舊寫法)
$target.on('click', {show: 'dd'}, function(e) {
console.log('click:', e.data.show);
});
*/
}
};
return this.each(function() {
handlers.play.call(handlers, opts);
});
};
})(jQuery);
// 使用
$('#test').hello({ size: 1 });
document (通用但性能稍差)body (某些瀏覽器不冒泡到 body)
$('#userList').on('click', '.delete-btn', function() {
const userId = $(this).data('id');
if (confirm('確定刪除?')) {
deleteUser(userId).then(() => {
$(this).closest('li').remove(); // 直接移除 DOM
});
}
});
// 異步添加新用戶
function addUser(user) {
$('#userList').append(`
${user.name}
`);
// 無需重新綁定,委託自動生效
}
// 傳遞數據
$('#btn').on('click', { userId: 123, action: 'delete' }, function(e) {
console.log(e.data.userId); // 123
console.log(e.data.action); // 'delete'
});
// 事件對象關鍵屬性
function handler(e) {
e.type; // 事件類型 'click'
e.target; // 觸發元素 (原生 DOM)
e.currentTarget; // 綁定元素 (等同 this)
e.delegateTarget; // 委託綁定元素
e.which; // 鍵碼/鼠標按鍵
e.pageX/Y; // 頁面座標
e.preventDefault(); // 阻止默認行為
e.stopPropagation(); // 阻止冒泡
e.stopImmediatePropagation(); // 阻止同元素其他處理器
return false; // 同時阻止默認和冒泡
}
hover → mouseenter mouseleavefocusin/focusout:冒泡版 focus/blurmousewheel/DOMMouseScroll → 統一為 wheelrequestAnimationFrame 節流高頻事件 (scroll/resize/mousemove){passive: true} (原生 JS,jQuery 3.0+ 支持).off() 清理