DIV CSS 佈局教程網

setTimeout 裡的 $(this) 為什麼失效?this 指向問題的正解
編輯:關於JavaScript     

寫延時關閉的下拉選單時,很多人會遇到同一個狀況:在 setTimeout 的閉包裡呼叫 $(this), jQuery 選擇器怎麼樣都選不到元素,但把這行程式搬到 setTimeout 外面就一切正常。這個現象的根因不是「setTimeout 不支援 jQuery 選擇器」,而是 this 的指向換了人。

出問題的寫法

 $('.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'});},300); } ); $('.dl_select dd').hover( function(){ clearTimeout(t2); $(this).css({'display':'block','cursor':'pointer'}); }, function(){ t3=setTimeout(function(){$(this).css({'display':'none'});},200); } ); 

正確的寫法

 $('.dl_select dt').hover( function(){ clearTimeout(t3); $(this).siblings('dd').css({'display':'block','cursor':'pointer'}); }, function(){ var $this=$(this).siblings('dd'); 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); } ); 

原因就在 this 的綁定規則

hover 傳入的函式由 jQuery 以元素為 this 呼叫,所以在函式「本體」內 this 指向 DOM 元素。但 setTimeout 內那層匿名函式是被計時器直接呼叫的,在非嚴格模式下 this 會變成 window,嚴格模式下則是 undefined。$window.siblings('dd') 自然什麼都選不到。

修正的關鍵是先「存起來」:在事件回呼中把 $(this) 存進 $this 變數,閉包會沿用它,於是 this 的問題被繞過了。除了這種寫法,也可以改用 setTimeout 的第三個參數或 bind 指定 this,或者在 ES5 之後用箭頭函式繼承外層的 this,效果相同。

順帶學到的一課

這類問題的共通教訓是:不要把 this 帶進任何非直接由物件呼叫的函式裡。養成在進入非同步流程前先把 this 存成區域變數的習慣,能省下大量排查時間。

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