2010-06-09 15 views
7

Estoy tratando de eliminar un atributo de título para un enlace en hover y luego agregarlo de vuelta en el mouse. Me gustaría pasar var hoverText al vuelo estacionario ...jquery hover pass variable a la función de devolución de llamada

Aquí está el código que tengo. ¿Algunas ideas?

$(".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); 

}); 

Respuesta

1

Ponga "hoverText" como variable global.

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

esto funciona, pero quiero evitar cualquier variable de las variables globales? –

+2

Eso es una solución terrible volteando ... Cuando se asigna Asterisco esa variable definitivamente no va a ser la misma. –

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'); 

}); 

El truco es:

$.data(this, 'title'); 

Al utilizar los datos, usted está almacenando de manera efectiva la variable en ese elemento DOM con el propósito expreso que acabas de describir. También podría resolver el problema declarando la variable $ this por encima de su función hover inicial, expandiendo el alcance para cubrir ambos.

+0

eso es lo que he estado tratando de averiguar cómo declararlo por encima de esto? ¿Alguna idea? –

+0

Exactamente lo que estaba buscando. Esto funciona muy bien para hacer simples consejos sobre herramientas. Agregue el marcado de información sobre herramientas al en la primera función, almacene el objeto DOM en una variable, almacene esa variable en el objeto $ .data, acceda a ella en la segunda función para atenuarla. – Mike

Cuestiones relacionadas