jQuery添加和删除$(window).scroll(function()?

时间:2010-11-29 17:35:56

标签: jquery window scrolltop

如何删除然后添加$(window).scroll?我需要存储一个变量并在某个事件之后重用它。

// 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     
});

谢谢。

1 个答案:

答案 0 :(得分:68)

您需要将该函数存储在变量中,然后使用off将其删除:

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