萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 事件綁定完全指南:bind()、簡寫方法與最佳實踐

bind() 方法詳解

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() 合成事件

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() { ... });

⚠️ hover() 重要注意事項

  • 底層綁定的是 mouseenter/mouseleave,**非** mouseover/mouseout
  • 不冒泡,不會因子元素觸發重複執行
  • 手動觸發需用 trigger('mouseleave') 而非 trigger('mouseout')

toggle() 合成事件(jQuery 1.9 移除)

注意: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');
    }
});

事件對象 event 統一封裝

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() { ... }); // 執行後自動解除

現代最佳實踐:使用 on()/off()

**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() 適合「只需響應一次」的場景(如引導提示)
copyright © 萬盛學電腦網 all rights reserved