事件.click会触发多次

时间:2019-07-27 16:33:05

标签: javascript jquery

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

p.s。对不起,我的英语不好

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以通过检查是否已经在运行回调来设置限制。一种方法是使用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个,但您可以尝试看看哪种方法最有效。

答案 2 :(得分:0)

我不知道这是多么的真实,但是确实有效。事件(单击)之后,删除元素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));
相关问题