$('.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') 可能匹配到錯誤元素。
setTimeout 回調執行時 this 指向 window(非嚴格模式)或 undefined(嚴格模式)。$(this).siblings('dd') 選擇結果可能不同。$this 捕獲的是 jQuery 對象引用,若後續代碼修改了該變量或 DOM 結構變化,行為不可預期。$('.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
}
);
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);
}
);
$('.dl_select dt').hover(
function() { clearTimeout(t3); $(this).siblings('dd').show(); },
function() {
(function($dd) {
t2 = setTimeout(function() { $dd.hide(); }, 300);
})($(this).siblings('dd'));
}
);
// 綁定在父容器,利用事件冒泡
$('.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 自動生效、定時器綁定在元素數據上避免全局變量污染、邏輯內聚。
任何異步回調中使用 this 或依賴當前 DOM 狀態的選擇器,都應在同步階段**立即計算並緩存**所需值/對象,再傳入異步回調。
核心原則:在同步階段「鎖定」所需的 DOM 引用/數值,通過閉包/箭頭函數/bind/IIFE 傳遞給異步回調。切勿在異步回調中重新查找 DOM 或依賴 this。事件委託模式能從根源上解決動態 DOM 與定時器管理的耦合問題。