在mouseover中将$(this)传递给setTimeout函数

Ree*_*ond 5 html javascript css jquery

如果用户在条形图上盘旋一秒钟,我试图在条形图上显示一些信息.这个网站上的答案让我到了这一步

var timer;
$(".session_hover").on({
     'mouseover': function () {
          timer = setTimeout(function () {
              $(this).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
          }, 1000);
     },
     'mouseout' : function () {
          clearTimeout(timer);
     }
});
Run Code Online (Sandbox Code Playgroud)

当我替换时,上面的代码工作$(this),$(".session_hover")但当然,它会触发$(".session_hover")页面上的所有其他代码.

我如何$(this)进入我的setTimeout函数,以便它只适用于我正在盘旋的div的子元素?

谢谢你的帮助!

p.s*_*w.g 9

尝试围绕变量创建一个闭包来捕获$(this),然后在你的函数中使用它:

 'mouseover': function () {
      var $this = $(this);
      timer = setTimeout(function () {
          $this.children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
      }, 1000);
 },
Run Code Online (Sandbox Code Playgroud)

请注意,在现代浏览器中,您还可以提供this参数setTimeout,如下所示:

 'mouseover': function () {
      timer = setTimeout(function (t) {
          $(t).children('.session_info').css({'top':175,'right':20}).fadeIn('fast');
      }, 1000, this);
 },
Run Code Online (Sandbox Code Playgroud)

但是,如果您希望在IE <9中使用它,则需要使用此MDN文章中描述的polyfill技术之一.