DIV CSS 佈局教程網

setTimeout 裡的 $(this) 失效?用閉包保存參照就能解決
編輯:JavaScript綜合知識     

寫延時效果時很容易遇到一個惱人的問題:在 setTimeout 的函式裡使用 jQuery 的 $(this), selector 就是抓不到東西。這個問題背後其實有清楚的原因,解法也很乾淨。

問題的根源:this 被換掉了

嚴格來說,並不是「setTimeout 不支援 jQuery 選擇器」,而是 setTimeout 延遲執行時,回呼函式裡的 this 已經不再是原本那個 DOM 元素了。在非嚴格模式下,它會變成全域物件 window,因此 $(this) 包裝的是 window,自然找不到 siblings()。

錯誤寫法

$('.dl_select dt').hover(
    function () {
        clearTimeout(t3);
        $(this).siblings('dd').css({ 'display': 'block', 'cursor': 'pointer' });
    },
    function () {
        t2 = setTimeout(function () {
            $(this).siblings('dd').css({ 'display': 'none' });  // 這裡的 this 已不是 dt
        }, 300);
    }
);
$('.dl_select dd').hover(
    function () {
        clearTimeout(t2);
        $(this).css({ 'display': 'block', 'cursor': 'pointer' });
    },
    function () {
        t3 = setTimeout(function () {
            $(this).css({ 'display': 'none' });
        }, 200);
    }
);

正確寫法:先把 this 存起來

$('.dl_select dt').hover(
    function () {
        clearTimeout(t3);
        $(this).siblings('dd').css({ 'display': 'block', 'cursor': 'pointer' });
    },
    function () {
        var $this = $(this).siblings('dd');   // 在 this 還正確時先存成變數
        t2 = setTimeout(function () {
            $this.css({ 'display': 'none' });
        }, 300);
    }
);
$('.dl_select dd').hover(
    function () {
        clearTimeout(t2);
        $(this).css({ 'display': 'block', 'cursor': 'pointer' });
    },
    function () {
        var $this = $(this);
        t3 = setTimeout(function () {
            $this.css({ 'display': 'none' });
        }, 200);
    }
);

其他幾種解法

除了用閉包保存變數,還有兩個常見做法:

  • 用 Function.prototype.bind 綁定 this:setTimeout(function () { $(this).css(...) }.bind(this), 300)。
  • 用箭頭函式繼承外層 this:setTimeout(() => { $(this).css(...) }, 300)。這是現在最推薦的寫法。

順序上也要注意:這類「移入展開、移出收合」的效果,一定要搭配 clearTimeout,而且計時器變數最好宣告在全域或外層函式,否則每次觸發都會產生新的計時器,滑鼠快速移動時就會出現動畫打架。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved