滚动事件被多次触发

当滚动距离底部 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); 

    }       

  }

});


UYOU
浏览 488回答 3
3回答

米脂

可能是滚动事件连续多次触发。因此,在实际触发 if 中的代码之前,当 window.scrollTop() 距底部 800,然后距底部 799,距底部 798 时,将调用您的函数。尝试重新设置 window.scrollTop(value) 以便它永远不会从底部超过 800。这样你的函数只被调用一次。

弑天下

您正在使用“if”条件,只要 $(window).scrollTop() + $(window).height() > $(document).height() - 800 这意味着每当&nbsp; &nbsp; $(window).scrollTop() + $(window).height()低于&nbsp; &nbsp; $(document).height() - 800&nbsp;该函数将始终被调用。尝试使用 '===' 而不是 '>' 这样循环只会针对特定值触发一次。您也可以尝试使用控件。可以说; 介绍&nbsp; &nbsp; var hasRun = 0; //increment this value once the condition&nbsp; &nbsp; // $(window).scrollTop() + $(window).height() > $(document).height() - 800&nbsp;&nbsp; &nbsp; //is true.&nbsp;每次减少 var hasRun 的值&nbsp; &nbsp; $(window).scrollTop() + $(window).height() < $(document).height() - 800&nbsp;是真的。请试试这个。&nbsp; &nbsp; &nbsp;$(window).scroll(function(event) {var hasRun = 0;if($(window).scrollTop() + $(window).height() > $(document).height() -&nbsp;800 ) {hasRun = hasRun + 1;}&nbsp;if($(window).scrollTop() + $(window).height() < $(document).height() -&nbsp;800 ) {hasRun = 0;}if(hasRun <= 0){// ajax call get data from server and append to the divvar id = $('#load_more_button').data('id');$('#load_more_button').html('<b>Loading...</b>');if (id >= 1) {load_data(id, _token);&nbsp;&nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;}});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript