[英]how to do one time trigger click with window.scroll jquery?
這是我的js代碼,用於從數據庫加載更多帖子的按鈕。
.getmore
是按鈕的類。 現在,我想進行無限滾動,以便用戶無需單擊該按鈕。
所以我添加了window.scroll
函數:
$('.getmore').trigger("click");
但一次點擊3次。 手動單擊該按鈕時,它可以正常工作。 但是使用滾動觸發器,它會獲得三倍的效果。
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() + $(window).height() > $(document).height() - 300) {
$('.getmore').trigger("click");
}
});
$('body').on('click','.getmore',function(){
var lastelement = $(this).attr('id');
$.ajax({
type: 'GET',
url: 'getmore.php',
data:'lastelement='+lastelement,
beforesend: function(){
$('.getmore').html('loading....');
},
success: function(data){
$('.getmore').remove();
$('#recs') .append(data) ;
}
});
});
});
如MDN所述:
由於滾動事件可以以很高的速度觸發,因此事件處理程序不應執行計算量大的操作,例如DOM修改。 相反,建議使用requestAnimationFrame,setTimeout或customEvent限制事件
他們提出的基本方法是檢查事件狀態的全局變量。 對於您的示例,您可以保存一個名為fetching
的全局變量,該變量在用戶滾動時設置為true
,而在success
回調中完成新數據的獲取后則設置為false
。 最后,如果fetching
為true
,則不允許“單擊” .getmore
。
閱讀文檔以獲取更多信息: https : //developer.mozilla.org/en-US/docs/Web/Events/scroll
嘗試這個 :
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()){
$('yourbuttonIDorClass').trigger('click');
}
});
遇到此類問題的典型方法是使用推論來排除導致問題的原因:。
排除.getmore類中有多少個元素。
console.log($('.getmore').length);
//Add this line under the .trigger('click');
如果大於1,則可能是您的問題。
排除調用窗口滾動回調的次數。
console.log('Scroll called');
//Add this line at the start of your $(window).scroll function.
如果滾動被調用了3次,這可能是您的問題
檢查您采用的事件委派方法不會引起任何奇怪的問題。
將$('body').on('click', '.getmore', function() {}
替換$('.getmore').click(function() {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.