繁体   English   中英

事件.click触发多次

[英]The event .click fires multiple times

在页面上,有一个ID为get-more-posts的链接,可通过单击加载文章的链接。 最初,它在屏幕之外。 任务是通过单击将屏幕滚动到该链接。 下面的代码可以满足您的需求。 但是该事件被多次调用。 当我滚动到该元素时,只需单击一下即可。

PS对不起我的英语不好

$(window).on("scroll", function() {
if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
    $('#get-more-posts').click();
}
});

尝试使用removeEventListener或将变量与标志一起使用,只是事件滚动一次脱离了更多

您可以通过检查是否已经在运行回调来设置限制。 一种方法是使用setTimeout函数,如下所示:

var throttled = null;
$(window).on("scroll", function() {
    if(!throttled){
        throttled = setTimeout(function(){
            if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
                $('#get-more-posts').click();
                throttled = null;
            }
        }.bind(window), 50);
    }
}.bind(window));

这是一个ES6版本,可以解决我提到的范围界定问题:

let throttled = null;
$(window).on("scroll", () => {
    if(!throttled){
        throttled = setTimeout(() => {
            if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
                $('#get-more-posts').click();
                throttled = null;
            }
        }, 50);
    }
});

setTimeout的最后一个参数是运行前的延迟。 我任意选择了50,但是您可以尝试看看哪种方法效果最好。

我不知道这是多么的真实,但是确实有效。 事件(单击)之后,删除元素ID,然后再次添加它,因此单击将执行一次。 将页面滚动到所需项目,再次单击,删除ID并再次添加。 有用。 有人可以派上用场吗?

window.addEventListener('scroll', throttle(callback, 50));
function throttle(fn, wait) {
 var time = Date.now();
 return function() {
   if ((time + wait - Date.now()) < 0) {
     fn();
     time = Date.now();
   }
 }
}
function callback() {
 var target = document.getElementById('get-more-posts');

if((($(window).scrollTop()+$(window).height())+650)>=$(document).height()){
               $('#get-more-posts').click();
               $("#get-more-posts").removeAttr("id");
             //$(".get-more-posts").attr("id='get-more-posts'");
       };         

}
window.removeEventListener('scroll', throttle(callback, 50));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM