【问题标题】:Jquery .removeClass not working inside setTimeoutJquery .removeClass 在 setTimeout 内不起作用
【发布时间】:2012-05-06 07:08:56
【问题描述】:

所以我有一个出现在悬停时的下拉导航,我试图在那里延迟以提高可用性。最初我使用的 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);});      

当我这样设置时:

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


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

警报可以完美运行,但 .removeClass 函数却不行。

我错过了什么吗?

【问题讨论】:

  • “off()”函数中this 的值将不是您需要的值。

标签: jquery navigation hover settimeout removeclass


【解决方案1】:

setTimeout里面的this不是li元素;我建议您使用接收函数的 setTimeout 重载,然后将变量设置为 this 以保留引用:

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

【讨论】:

    【解决方案2】:

    您的off 函数:

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

    setTimeout() 调用时,不会有正确的this 变量 - 在大多数(所有?)浏览器上它将this 设置为window

    您需要一个额外的闭包来包装原始的 this 并将其传递给该计时器函数:

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

    注意:不要对setTimeout() 使用字符串参数!

    【讨论】:

      【解决方案3】:

      问题在于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>
      

      【讨论】:

        猜你喜欢
        • 2020-08-27
        • 2019-01-29
        • 2014-03-25
        • 2016-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-16
        相关资源
        最近更新 更多