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

Dee*_*Dee 30 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     
});
Run Code Online (Sandbox Code Playgroud)

谢谢.

And*_*y E 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);
});
Run Code Online (Sandbox Code Playgroud)

  • 我认为这应该是:$("#itemUnbind").click(function(){$(window).unbind("scroll",scrollHandler);}); (3认同)