jQuery add and remove $(window).scroll(function()?

有些话、适合烂在心里 提交于 2019-12-03 14:35:28

问题


How can I remove and then add the $(window).scroll? I need to store a variable and reuse it after some event.

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

Thank you.


回答1:


You need to store the function in a variable and then use off to remove it:

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


来源:https://stackoverflow.com/questions/4306387/jquery-add-and-remove-window-scrollfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!