【发布时间】:2021-03-29 14:21:58
【问题描述】:
我正在尝试加载更多滚动项目。该代码有效,用户到达页面底部。每次用户滚动到页面底部时,都会加载 9 个项目。
当我尝试在用户到达页面底部之前加载 9 个项目时出现此问题。然后等待这些项目被加载,然后再次检查条件 (currentScroll >= goal)。
此时,只要条件为 TRUE (currentScroll >= goal),所有项目都会立即加载。 我猜这是因为 currentScroll 变量在滚动时不断计数,而第一组项目尚未加载。结果 $(document).height() 仍然相同,这会影响目标变量:var goal = $(document).height() - $(window).height();
我尝试使用 while 循环(请参阅我的代码中的注释部分),但代码崩溃了。
有没有什么办法可以让程序在条件为TRUE的情况下等待该组item(9个item)被加载然后再检查?
$(window).scroll(function() {
var currentScroll = $(window).scrollTop();
var goal = $(document).height() - $(window).height(); // Bottom of the page
goal = goal*0.5; // Load more items before reach bottom of the page
// The following parts check if all the items are loaded. That works!!
var result_count = document.getElementsByClassName('yacht-count')[0].innerHTML
total_results_to_show = group_of_villas_showed*results_to_show;
if(result_count/total_results_to_show<=1){
goal = currentScroll*2;
console.log("Finish");
}
// Check if the current scroll is greater than the setted goal
if (currentScroll >= goal){
console.log("start loading villas");
ajaxGet(guests_value,destinations_value,sort_by,current_page);
current_page++;
group_of_villas_showed+=1;
console.log("loading villas");
}
// With the use of this Loop program crashes
/*
while(currentScroll >= goal){
goal = $(document).height() - $(window).height();
var currentScroll = $(window).scrollTop();
goal = goal*0.5;
}
*/
});
ajaxGet = (guests_value,destinations_value,sort_by,page, replace = false) => {
$.ajax({
type: 'GET',
url: ajax_url,
data: {
guests: guests_value,
destination: destinations_value,
sort_by: sort_by,
page:page,
},
dataType: 'json',
beforeSend: function(){
$('#loading-image').removeClass('hide');
$('.yachts-search-page').addClass('loading-more');
},
success: function (data) {
//console.log('ajax success');
$('.yachts-search-page').removeClass('loading-more');
$('#loading-image').addClass('hide');
if(replace){
$('body .load-more-wrapper').show();
$('body .yachts-inner').html(data.content);
current_page = 1;
}
else
$('body .yachts-inner').append(data.content);
$('body .yacht-count').text(data.yacht_count);
newQueryString(guests_value,destinations_value,sort_by,page);
},
error: function(data){
//console.log('error wtf');
}
});
}
【问题讨论】:
-
我会删除循环并尝试限制或消除滚动事件功能。这可能会解决您的问题,因为这听起来可能与您的滚动事件过度触发有关。您可能还想检查函数开头的页面位置,如果不满足条件则返回 null 以防止发生任何其他操作。由于没有去抖动或限制滚动事件,Twitter 几年前就遇到了主要的性能问题。
-
它几乎可以是任何东西。在 jsfiddle 或可运行脚本中测试代码更改要容易得多。这有帮助吗? stackoverflow.com/questions/10662528/… 或 stackoverflow.com/questions/13237555/… 或 stackoverflow.com/questions/13057910/…
标签: javascript jquery ajax