亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

滾動事件被多次觸發

滾動事件被多次觸發

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 

該函數將始終被調用。嘗試使用 '===' 而不是 '>' 這樣循環只會針對特定值觸發一次。


您也可以嘗試使用控件??梢哉f; 介紹


    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 關注
  • 473 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號