bind() 是 jQuery 早期核心事件綁定方法(jQuery 3.0+ 已棄用,建議用 on()),語法:
$(selector).bind(eventType, [eventData], handler)
| 參數 | 說明 |
|---|---|
eventType | 事件類型:click、mouseover、keydown 等,**不帶 on 前綴** |
eventData | 可選,傳遞給處理函數的額外數據,可在 event.data 訪問 |
handler | 事件處理函數,this 指向當前 DOM 元素 |
$(function() {
$('#panel h5.head').bind('click', function() {
var $content = $(this).next();
if ($content.is(':visible')) {
$content.hide();
} else {
$content.show();
}
});
});
| 類別 | 事件 |
|---|---|
| 鼠標 | click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, contextmenu |
| 鍵盤 | keydown, keypress, keyup |
| 表單 | focus, blur, change, select, submit, reset |
| 窗口 | load, resize, scroll, unload, error |
| 觸摸 | touchstart, touchmove, touchend, touchcancel |
jQuery 為常用事件提供了直接方法,等同於 bind('event', fn):
// 等價寫法
$('#btn').click(handler); // bind('click', handler)
$('#box').hover(enterFn, leaveFn); // bind('mouseenter') + bind('mouseleave')
$('#input').focus(handler); // bind('focus', handler)
// ... 所有常用事件均有對應簡寫
hover(enterHandler, leaveHandler) 同時綁定 mouseenter 和 mouseleave:
$('#panel h5').hover(
function() { $(this).next().show(); }, // mouseenter
function() { $(this).next().hide(); } // mouseleave
);
// 等價於
$('#panel h5').on('mouseenter', function() { ... })
.on('mouseleave', function() { ... });
mouseenter/mouseleave,**非** mouseover/mouseouttrigger('mouseleave') 而非 trigger('mouseout')注意:toggle(fn1, fn2...) 作為點擊切換行為在 **jQuery 1.9+ 已移除**(與動畫 toggle() 衝突)。現代寫法請自行實現:
// 現代替代:使用標誌變量
let toggled = false;
$('#btn').on('click', function() {
toggled = !toggled;
if (toggled) {
$(this).next().show();
$(this).addClass('active');
} else {
$(this).next().hide();
$(this).removeClass('active');
}
});
jQuery 統一了跨瀏覽器的事件對象,常用屬性/方法:
$(selector).on('click', function(event) {
event.preventDefault(); // 阻止默認行為(如鏈接跳轉、表單提交)
event.stopPropagation(); // 阻止事件冒泡
event.stopImmediatePropagation(); // 阻止同元素其他處理器執行
event.target; // 觸發事件的元素
event.currentTarget; // 綁定事件的元素 (等同 this)
event.which; // 統一的鍵碼/鼠標鍵
event.pageX, event.pageY; // 相對文檔座標
event.data; // bind 時傳遞的額外數據
});
$('#btn').bind('click', { user: 'Alice', id: 123 }, function(event) {
console.log(event.data.user); // "Alice"
console.log(event.data.id); // 123
});
// 多次綁定同一事件,按順序執行
$('#btn').on('click', fn1).on('click', fn2).on('click', fn3);
// 移除特定處理器(需保存引用)
const handler = function() { ... };
$('#btn').on('click', handler);
$('#btn').off('click', handler); // 只移除 handler
// 移除所有 click
$('#btn').off('click');
// 僅執行一次
$('#btn').one('click', function() { ... }); // 執行後自動解除
**jQuery 1.7+ 推薦統一使用 on()/off()** 替代 bind()/unbind()/live()/delegate():
// 直接綁定
$(selector).on('click', handler);
// 事件委託(動態元素、性能優化)
$(parent).on('click', '.child-selector', handler);
// 移除
$(selector).off('click', handler);
$(parent).off('click', '.child-selector', handler);
bind() 歷史地位,但**新項目請用 on()/off()**mouseenter/leave (hover 底層) 與 mouseover/out (冒泡)event.data 傳遞上下文,避免閉包陷阱one() 適合「只需響應一次」的場景(如引導提示)