Jquery .removeClass在setTimeout中不起作用

Zac*_*ady 0 navigation jquery hover settimeout removeclass

所以我在悬停时出现了一个下拉导航,我试图在那里延迟以提高可用性.最初我使用的是hoverIntent,除了IE8及以下版本以外,它在任何地方都能很好地工作.

所以我试图用普通的旧Javascript来做延迟,但是setTimeout函数不会调用我的jQuery.

var J = jQuery.noConflict();

 J(".navigation li").hover(function(){J(this).addClass("hover");},function(){setTimeout("J(this).removeClass('hover');",500);});      
Run Code Online (Sandbox Code Playgroud)

当我这样设置时:

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


J(".navigation li").hover(function(){J(this).addClass("hover");},function(){setTimeout("off()",500);}); 
Run Code Online (Sandbox Code Playgroud)

警报完美但不是.removeClass函数.

我错过了什么吗?

jor*_*hmv 8

this里面setTimeout不是李元素; 我建议你使用接收函数的setTimeout重载,并在设置变量之前this保留一个引用:

J(".navigation li").hover(function(){
   J(this).addClass("hover");
},
function(){
  var self = this;
  setTimeout(function() {
         J(self).removeClass('hover');
  },500);
});
Run Code Online (Sandbox Code Playgroud)