我想你做得差不多。
得到
无限滚动
使用时,需要在第一个脚本的底部添加以下行:
var $window = $( window );
var $document = $( document );
$window.scroll(function () {
// In some cases `$document.height()` is equal to `$window.height()`,
// so you can use the upper condition
//if ( ( window.innerHeight + window.scrollY ) >= document.body.offsetHeight - 300 ) {
if ( $window.scrollTop() >= $document.height() - $window.height() - 300 ) {
console.log('infinite scroll');
flag += 4; // AUTO IN INCREMENT
filter_data();
}
});
小提琴在这里:
到
阻止多个请求并停止无限滚动
如果已加载所有数据,则可以添加以下两个信号量:
fetching
和
done
// init at the top of your script
var fetching = false;
var done = false;
// add these two lines at the beginning of filter_data
function filter_data() {
// prevent concurrent requests
if(fetching === true) { return; }
fetching = true;
// ...
// condition in the scroll handler should look like this
if (
$window.scrollTop() >= $document.height() - $window.height() - 300 &&
fetching === false && done === false
) {
// ...
// ajax success and error handler
.done( function (data) {
console.log('data received');
// append new data
if(data !== '<h3>No Data Found</h3>') {
//$('.filter_data').html(data); // override
$('.filter_data').append(data); // append
}
// we reached the end, no more data
else {
if(flag === 0) $('.filter_data').append(data); // display initially "no data found"
done = true;
}
flag += 4; // move here. increment only once on success
fetching = false; // allow further requests again
})
.fail( function( error ) {
console.log( 'An error occurred while fetching', error )
// TODO: some error handling
});
https://jsfiddle.net/fus6hyar/
不起作用的可能原因:
-
-
.done( function (data) {
console.log('data received', data);
// ...
})
.fail( function( error ) {
console.log( 'An error occurred while fetching', error )
// some error handling ...
});
-
如果数据已接收但仍无法呈现,请检查选择器是否仍然正确/可用:
.done( function (data) {
console.log('data received', data);
console.log($('.filter_data')); // can this element be found?
// ...
})
如果所有这些都不起作用,可以尝试在js脚本的开头添加更多日志,比如
console.log($(window))
检查是否正确初始化了JQuery。最后,您可以将html标记添加到问题中,可能有错误。