2011-05-04 14 views
7

Tengo algunas Código jQuery de la siguiente manera:jQuery anidado Esto hace referencia a

$("#sh-zone-button-cart-menu").live("click", function(event) 
{ 
    event.preventDefault(); 
    $("#sh-zone-cart-menu").toggle(0, function(){ 
     if($(this).is(":visible")){ 
      $(this).siblings(".sh-zone-button-link-menu-content").hide(); 
      $("#sh-zone-button-cart-menu").parent().removeClass("current"); 
      //need to reference (this) for $("#sh-zone-button-cart-menu") here 
     }    
    }); 
    $("#sh-zone-button-cart-menu").parent().toggleClass("current"); 
}); 

Estoy intentando acceder a la presente petición de mi clic inicial desde el interior de otro sub-elemento es decir, me gustaría conseguir la esta referencia que habría estado disponible justo después de la primera llave de mi método live(). Sin embargo, necesito acceder a él desde otro subelemento, es decir, dentro de mi método toggle().

¿Cómo puedo hacer esto?

Gracias.

+0

Estoy sorprendido de que no se haya votado más ... me salvaste un poco de tiempo. ¡No sabía que las funciones de JavaScript lambda podían capturar variables locales como esta! – RonLugge

Respuesta

11

Guardar this como una variable local:

$("#sh-zone-button-cart-menu").live("click", function(event) { 
    // This line saves the current 'this' as a local variable 
    // that can be accessed by inner functions   
    var thisInClick = this; 
    event.preventDefault(); 
    $("#sh-zone-cart-menu").toggle(0, function(){ 
     if($(this).is(":visible")){ 
      $(this).siblings(".sh-zone-button-link-menu-content").hide(); 
      $("#sh-zone-button-cart-menu").parent().removeClass("current"); 
      //need to reference (this) for $("#sh-zone-button-cart-menu") here 
      $(thisInClick).doSomething(); 
     }    
    }); 
    $("#sh-zone-button-cart-menu").parent().toggleClass("current"); 
}); 
+0

Gracias Juan. Esto resolvió el problema. Acabo de usar var elem = $ (this) y luego lo llamé donde lo necesitaba. Aclamaciones. –

+0

Acaba de entrar en jQuery y se encontró con un problema similar. Este concepto me ahorró muchos dolores de cabeza. – brooklynsweb

1

Puede guardar una referencia a this en una variable, por lo que puede usarlo más tarde.

$("#sh-zone-button-cart-menu").live("click", function(event) 
{ 
    event.preventDefault(); 
    var that = this; 
    $("#sh-zone-cart-menu").toggle(0, function(){ 
     if($(this).is(":visible")){ 
      $(this).siblings(".sh-zone-button-link-menu-content").hide(); 
      $("#sh-zone-button-cart-menu").parent().removeClass("current"); 
      //need to reference (this) for $("#sh-zone-button-cart-menu") here 
      $(that).show(); // <= "that" is sh-zone-button-cart-menu 
     }    
    }); 
    $("#sh-zone-button-cart-menu").parent().toggleClass("current"); 
}); 
3

Aquí hay una muestra diluida para mostrarle la técnica general.

$("#sh-zone-button-cart-menu").live("click", function(event) 
{ 
    var that = this; 

    $("#sh-zone-cart-menu").toggle(0, function(){ 
     alert($(that).attr('id')); 
     alert($(this).attr('id')); 
    }); 

}); 
0

Dentro de la devolución de llamada en vivo, tiene otro método 'alternar'. La palabra clave this aquí se refiere al elemento específico con ID de $ ('# sh-zone-cart-menu').

Si desea acceder a esa referencia, simplemente use ese selector.

+1

El punto es que no quiere tener que volver a seleccionar ya que ya estaba disponible como 'this'. No es necesario hacer trabajo adicional. –

Cuestiones relacionadas