萬盛學電腦網

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

setTimeout 中使用 jQuery 選擇器失效?閉包捕獲 this 的正確姿勢

問題現場

$('.dl_select dt').hover(
  function() {
    clearTimeout(t3);
    $(this).siblings('dd').show();
  },
  function() {
    var $this = $(this).siblings('dd'); // 錯誤:this 指向 dt,但 siblings('dd') 在 setTimeout 時可能已變
    t2 = setTimeout(function() { $this.hide(); }, 300);
  }
);

表面看已用變量緩存 $this,但若在 hover 的 mouseleave 階段,$(this) 已不再是預期元素(事件委託、動態 DOM 等情況),且 siblings('dd') 可能匹配到錯誤元素。

根本原因

  1. this 丟失:setTimeout 回調執行時 this 指向 window(非嚴格模式)或 undefined(嚴格模式)。
  2. 選擇器上下文變化:若 DOM 結構變化,$(this).siblings('dd') 選擇結果可能不同。
  3. 閉包捕獲引用而非值:變量 $this 捕獲的是 jQuery 對象引用,若後續代碼修改了該變量或 DOM 結構變化,行為不可預期。

正確解決方案

方案一:箭頭函數保留外層 this(ES6+ 推薦)

$('.dl_select dt').hover(
  function() { clearTimeout(t3); $(this).siblings('dd').show(); },
  function() {
    const $dd = $(this).siblings('dd'); // 立即計算並緩存 jQuery 對象
    t2 = setTimeout(() => $dd.hide(), 300); // 箭頭函數無 this,捕獲外層 $dd
  }
);

方案二:bind 綁定 this(ES5)

function hideDD($dd) { $dd.hide(); }

$('.dl_select dt').hover(
  function() { clearTimeout(t3); $(this).siblings('dd').show(); },
  function() {
    const $dd = $(this).siblings('dd');
    t2 = setTimeout(hideDD.bind(null, $dd), 300);
  }
);

方案三:立即執行函數(IIFE)創建獨立作用域

$('.dl_select dt').hover(
  function() { clearTimeout(t3); $(this).siblings('dd').show(); },
  function() {
    (function($dd) {
      t2 = setTimeout(function() { $dd.hide(); }, 300);
    })($(this).siblings('dd'));
  }
);

方案四:事件委託 + data 屬性(最穩健)

// 綁定在父容器,利用事件冒泡
$('.dl_select').on('mouseenter', 'dt', function() {
  clearTimeout($(this).data('hideTimer'));
  $(this).siblings('dd').show();
}).on('mouseleave', 'dt', function() {
  const $dd = $(this).siblings('dd');
  const timer = setTimeout(() => $dd.hide(), 300);
  $(this).data('hideTimer', timer); // 存儲 timer 供下次 mouseenter 清除
});

優勢:動態添加的 dt 自動生效、定時器綁定在元素數據上避免全局變量污染、邏輯內聚。

同理適用於 setInterval、requestAnimationFrame、Promise.then、事件處理器

任何異步回調中使用 this 或依賴當前 DOM 狀態的選擇器,都應在同步階段**立即計算並緩存**所需值/對象,再傳入異步回調。

總結

核心原則:在同步階段「鎖定」所需的 DOM 引用/數值,通過閉包/箭頭函數/bind/IIFE 傳遞給異步回調。切勿在異步回調中重新查找 DOM 或依賴 this。事件委託模式能從根源上解決動態 DOM 與定時器管理的耦合問題。

copyright © 萬盛學電腦網 all rights reserved