36

如何删除然后添加$(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     
});

谢谢你。

4

1 回答 1

77

您需要将该函数存储在一个变量中,然后使用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);
});
于 2010-11-29T17:38:31.847 回答