2016-12-31 37 views
1

我有这段代码来显示我创建的工具提示。它显示在鼠标悬停,延迟2秒后。

/* Custom Shop Page Toolip */ 
var timeout; 
$('.product-bottom-info-container').hover(
    var that = this; 
    function(e) { 
     timeout = setTimeout(function() { 
      that.find('.product-custom-tooltip-container').css({ 
       display: 'inline-block', 
       position: 'fixed', 
       zIndex: '5000', 
       margin: '10px', 
       whiteSpace: "nowrap" 
      }).position({ 
       my: "right top", 
       at: "left bottom", 
       of: e, 
       collision: "fit" 
      }); 
     }, 2000); 
    }, 
    function() { 
     clearTimeout(timeout); 
     that.find('.product-custom-tooltip-container').hide(); 
    } 
); 

调用setTimeout()后,我不再能够访问$(this),这是引用。产品底部-信息容器选择。

所以我试图创建一个变量,而不是 - var that = $(this)。我在该行发现错误意外令牌var。我也尝试过var that = this,这也行不通。

如何在setTimeout()函数中访问$(this)

我一直在阅读各种各样的例子,namely this one,它似乎适用于某些,但它不适合我。

回答

0

您的代码的问题是语法错误。虽然这样做,你也没有使用$这里:

/* Custom Shop Page Toolip */ 
var timeout; 
$('.product-bottom-info-container').hover(// Here you should give your parameters, and you cannot have a ; here. 
    var that = this; 
    function(e) { 
     timeout = setTimeout(function() { 
      that.find('.product-custom-tooltip-container').css({ 
       display: 'inline-block', 
       position: 'fixed', 
       zIndex: '5000', 
       margin: '10px', 
       whiteSpace: "nowrap" 
      }).position({ 
       my: "right top", 
       at: "left bottom", 
       of: e, 
       collision: "fit" 
      }); 
     }, 2000); 
    }, 
    function() { 
     clearTimeout(timeout); 
     that.find('.product-custom-tooltip-container').hide(); 
    } 
); 

改变你的代码的下面应该工作:

var timeout; 
$('.product-bottom-info-container').hover(function(e) { 
    // 1. Wrap your this inside $(). 
    var that = $(this); 
    timeout = setTimeout(function() { 
    that.find('.product-custom-tooltip-container').css({ 
     display: 'inline-block', 
     position: 'fixed', 
     zIndex: '5000', 
     margin: '10px', 
     whiteSpace: "nowrap" 
    }).position({ 
     my: "right top", 
     at: "left bottom", 
     of: e, 
     collision: "fit" 
    }); 
    }, 2000); 
}, function() { 
    clearTimeout(timeout); 
    // 2. You can use $(this) here as it is the second function, and this refers to the element that triggered the event. 
    $(this).find('.product-custom-tooltip-container').hide(); 
}); 

需要做的两两件事是:

  1. 将您的this裹在$(this)的内部。
  2. .hover()函数的第二个参数中使用$(this)
+0

不知道为什么投票,为我工作。非常感谢 – anthonyCam

+0

@ItsMeMike我已经更新了更改。请看看它。 ':''不要忘记在10分钟内接受我的回答。 –

+1

当然,再次感谢。有用的信息 – anthonyCam