2012-04-25 292 views
0

所以我有一個下拉導航出現在懸停,我試圖得到延遲在那裏,以提高可用性。最初我使用的是hoverIntent,除了IE8和以下版本外,其他任何地方都可以使用hoverIntent。jQuery的.removeClass不工作setTimeout

所以相反,我試圖用普通的舊Javascript做延遲,但setTimeout函數不會調用我的jQuery。

var J = jQuery.noConflict();

J(".navigation li").hover(function(){J(this).addClass("hover");},function(){setTimeout("J(this).removeClass('hover');",500);});  

當我設置它是這樣的:

function off(){J(this).removeClass("hover"); alert("hello");} 


J(".navigation li").hover(function(){J(this).addClass("hover");},function(){setTimeout("off()",500);}); 

警報完美的作品,但不是.removeClass功能。

我錯過了什麼嗎?

+1

請重新格式化您的代碼 – Alnitak 2012-04-25 15:05:28

+3

的'this'中的價值的古範圍的「關閉()」函數不會是你需要它是。 – Pointy 2012-04-25 15:06:13

回答

5

this裏面的setTimeout不是li元素;我建議你使用接收功能,並設置前一個變量來this setTimeout的過載,以保持一個參考:

J(".navigation li").hover(function(){ 
    J(this).addClass("hover"); 
}, 
function(){ 
    var self = this; 
    setTimeout(function() { 
     J(self).removeClass('hover'); 
    },500); 
}); 
1

off功能:

function off() { 
    J(this).removeClass("hover"); 
    alert("hello") 
} 

不會有正確的this變量當被setTimeout()調用 - 在大多數(所有)瀏覽器上,它將this設置爲window

你需要一個附加的封閉包裝的原始this並把它傳遞給計時功能:

J(".navigation li").hover(
    function() { 
     J(this).addClass("hover"); 
    }, 
    function() { 
     var that = this; 
     setTimeout(function() { 
      off.apply(that); 
     }, 500); 
    } 
); 

注:請不要使用字符串參數來setTimeout()

0

問題是this指的是超時回調的範圍內的不同內容。

最簡單的解決辦法是提供使用jQuery.proxy([function],[scope])

<html> 
    <head> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
     <script> 
      var f = function(){ 
       console.log(this.id); 
      }; 

      $(function() { 
       $("div").click(function() { 
        setTimeout($.proxy(f,this), 1000); 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
     <div id="a">a</div> 
     <div id="b">b</div> 
    </body> 
</html>