萬盛學電腦網

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

jQuery .on() 事件綁定全面指南:委託、多事件、數據傳遞、命名空間

.on() 統一事件綁定 API

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 });

事件委託最佳實踐

為什麼委託優於直接綁定?

  • 動態元素自動生效,無需重新綁定
  • 減少內存佔用:1 個監聽器替代 N 個
  • 避免頻繁綁定/解綁導致的內存洩漏

委託容器選擇原則

  1. 最近的靜態父容器 (最佳性能)
  2. document (通用但性能稍差)
  3. 避免 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 mouseleave
    • focusin/focusout:冒泡版 focus/blur
    • mousewheel/DOMMouseScroll → 統一為 wheel

    性能優化技巧

    1. 使用 requestAnimationFrame 節流高頻事件 (scroll/resize/mousemove)
    2. 被動事件監聽器 {passive: true} (原生 JS,jQuery 3.0+ 支持)
    3. 銷毀組件時 .off() 清理
    4. 避免在循環中綁定,改用委託
    copyright © 萬盛學電腦網 all rights reserved