问题:
I'm trying to implement lazy scrolling in my script and it's working well up until it reaches the end and I want to stop it from making extra requests.
I've added an eve...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I'm trying to implement lazy scrolling in my script and it's working well up until it reaches the end and I want to stop it from making extra requests.
I've added an event listener to my code using:
window.addEventListener("scroll", _.throttle(checkScroll, 500));
However, when I try to remove it, it still seems to keep listening and acting on the event.
I've tried:
if (json.articles.length == 0) {
$(".articles").append("<br>That's all folks!");
window.removeEventListener("scroll", _.throttle(checkScroll, 500));
}
and
if (json.articles.length == 0) {
$(".articles").append("<br>That's all folks!");
window.off("scroll");
}
but neither seem to be working.
回答1:
If you add the event listener using plain Javascript, the only way to remove it would be to save a reference to the result of calling _.throttle
that you pass to addEventListener
:
const handler = _.throttle(checkScroll, 500);
window.addEventListener("scroll", handler);
// ...
window.removeEventListener("scroll", handler);
You could only do something like window.off('scroll')
if you also add the handler using jQuery (eg $(window).on(...)
and then $(window).off(...)
). If you add the handler with Javascript, jQuery's off
won't be usable.
回答2:
You can add the event handler in jQuery using on
and remove it using off
. Here's a fiddle to illustrate it.
$(window).on('scroll', function(ev) { //add handler
...
})
$(window).off('scroll', function(ev) { //remove handler
...
})