2010-06-09 40 views
7

我想刪除懸停的鏈接的標題屬性,然後將其添加回鼠標。我想通過var hoverText將鼠標懸停在外......jquery懸停通過變量回調函數

這是我的代碼。有任何想法嗎?

$(".icon a").hover(function() { 
    $this = $(this); 
    var hoverText = $.data(this, 'title', $this.attr('title'));        
    $(this).find("em").animate({opacity: "show", top: "-35"}, "slow"); 
    $(this).find("em").text(hoverText);  

    $this.removeAttr('title');  


}, function(hoverText) {    

    $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");  
    $(this).attr("title", hoverText); 

}); 

回答

1

將「hoverText」作爲全局變量。

var hoverText = ''; 
$(".icon a").hover(function() { 
    $this = $(this); 
    hoverText = $.data(this, 'title', $this.attr('title'));        
    $(this).find("em").animate({opacity: "show", top: "-35"}, "slow"); 
    $(this).find("em").text(hoverText);  

    $this.removeAttr('title');  


}, function() {    

    $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");  
    $(this).attr("title", hoverText); 

}); 
+1

這工作,但我想遠離全局變量任何想法? – 2010-06-09 20:27:39

+2

這是一個翻轉可怕的解決方案...當分配徘徊變量絕對不會保持不變。 – 2012-02-24 03:36:53

6
$(".icon a").hover(function() { 
    $this = $(this); 
    $.data(this, 'title', $this.attr('title'));        
    $(this).find("em").animate({opacity: "show", top: "-35"}, "slow"); 
    $(this).find("em").text(hoverText);  

    $this.removeAttr('title');  


}, function(hoverText) {    

    $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");  
    $(this).attr("title", $.data(this, 'title'); 

}); 

的訣竅是:

$.data(this, 'title'); 

當您使用的數據,你就有效地存儲爲您剛纔描述的明確目的是DOM元素的變量。您也可以通過在初始懸停函數上面聲明$ this變量來解決問題,擴大範圍以涵蓋兩者。

+0

這就是我一直在試圖弄清楚如何在上面聲明它?有什麼想法嗎? – 2010-06-09 20:17:58

+0

正是我在找的東西。這對於做簡單的工具提示非常有用。在第一個函數中將工具提示標記附加到,將DOM對象存儲在一個變量中,將該變量存儲在$ .data對象中,在第二個函數中訪問它以使其淡出。 – Mike 2011-08-16 01:00:37