为了账号安全,请及时绑定邮箱和手机立即绑定

滚动事件被多次触发

滚动事件被多次触发

UYOU 2021-08-26 16:45:11
当滚动距离底部 800px 时,我正在调用一个函数。它多次调用该函数,但我只想调用该函数一次,然后加载一些数据,当我转到 800px 表单底部时再次加载该函数,然后它应该只调用该函数一次。该函数名称是load_data().$(window).scroll(function(event) {  if($(window).scrollTop() + $(window).height() > $(document).height() -     800 ) {    // ajax call get data from server and append to the div    var id = $('#load_more_button').data('id');    $('#load_more_button').html('<b>Loading...</b>');    if (id >= 1) {     load_data(id, _token);     }         }});
查看完整描述

3 回答

?
米脂

TA贡献1836条经验 获得超3个赞

可能是滚动事件连续多次触发。因此,在实际触发 if 中的代码之前,当 window.scrollTop() 距底部 800,然后距底部 799,距底部 798 时,将调用您的函数。

尝试重新设置 window.scrollTop(value) 以便它永远不会从底部超过 800。这样你的函数只被调用一次。


查看完整回答
反对 回复 2021-08-26
?
弑天下

TA贡献1818条经验 获得超8个赞

您正在使用“if”条件,只要 $(window).scrollTop() + $(window).height() > $(document).height() - 800 这意味着每当


    $(window).scrollTop() + $(window).height()

低于


    $(document).height() - 800 

该函数将始终被调用。尝试使用 '===' 而不是 '>' 这样循环只会针对特定值触发一次。


您也可以尝试使用控件。可以说; 介绍


    var hasRun = 0; //increment this value once the condition

    // $(window).scrollTop() + $(window).height() > $(document).height() - 800 

    //is true. 

每次减少 var hasRun 的值


    $(window).scrollTop() + $(window).height() < $(document).height() - 800 

是真的。请试试这个。


     $(window).scroll(function(event) {

var hasRun = 0;

if($(window).scrollTop() + $(window).height() > $(document).height() - 

800 ) {

hasRun = hasRun + 1;

}

 if($(window).scrollTop() + $(window).height() < $(document).height() - 

800 ) {

hasRun = 0;

}

if(hasRun <= 0){

// ajax call get data from server and append to the div

var id = $('#load_more_button').data('id');

$('#load_more_button').html('<b>Loading...</b>');

if (id >= 1) {

load_data(id, _token);  

}       

}

});


查看完整回答
反对 回复 2021-08-26
  • 3 回答
  • 0 关注
  • 442 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信