2010-11-29 24 views
27

¿Cómo puedo quitar y añadir el $(window).scroll? Necesito para almacenar una variable y reutilizarlo después de algún evento.

// here i store my var 
$(window).scroll(function(){ 
    myScroll = $(window).scrollTop() 
}); 

$("#itemUnbind").click(function(){ 
    // here i need to remove the listener   
}); 

$("#itemBind").click(function(){ 
    // here i need to add listener again  
}); 

Gracias .

Respuesta

63

es necesario almacenar la función en una variable y luego usar off para eliminarlo:

var scrollHandler = function(){ 
    myScroll = $(window).scrollTop(); 
} 

$("#itemBind").click(function(){ 
    $(window).scroll(scrollHandler); 
}).click(); // .click() will execute this handler immediately 

$("#itemUnbind").click(function(){ 
    $(window).off("scroll", scrollHandler); 
}); 
+0

gracias ... que está bien para mí – Dee

+1

@Dee - si esto funciona para usted, por favor marcarlo como la respuesta haciendo clic en el ícono "marcar". – Fenton

+3

Creo que esto debería ser: $ ("# itemUnbind"), haga clic en (función() { $ (ventana) .unbind ("scroll", scrollHandler); }); –

Cuestiones relacionadas