我有以下代码在用户滚动到屏幕底部时触发。唯一的问题是我希望Ajax调用只触发一次。我的代码是:
var w = $(window);
window.onscroll = function(ev) {
if ($(document).height() - w.height() == w.scrollTop()) {
$('#loading-image').show();
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
}
});
}
};
答案 0 :(得分:0)
最简单的方法是添加全局变量并以这种方式检查:
var w = $(window);
var BOTTOM_REACHED = false;
window.onscroll = function(ev) {
if ($(document).height() - w.height() == w.scrollTop() && !BOTTOM_REACHED) {
BOTTOM_REACHED = true;
$('#loading-image').show();
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
BOTTOM_REACHED = false;
}
});
}
};
答案 1 :(得分:-1)
您可以尝试这样:
var bottom_reached = false;
$(window).scroll(function(){
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
bottom_reached = true;
$('#loading-image').show();
if(bottom_reached)
{
bottom_reached = false;
$.ajax({
url: "page-2.html",
cache: false,
success: function(result){
$("#part2").html(result);
console.log();
},
complete: function(){
$('#loading-image').hide();
}
});
}
}
});