2016-12-31 34 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