我有以下函数在我的页面上无限滚动。似乎一旦我转到触发 if 语句的页面,之后我访问的每个页面都将继续触发滚动处理程序。我知道这一点,因为每次滚动时,每隔一个页面都会将"窗口滚动"打印到控制台,但不触发"if 语句 true"。如何使窗口.scroll仅适用于具有#infinite-scrolling
的页面?
function initPagination() {
var paginate = function(buttonPress) {
var url = $('.pagination .next_page').attr('href');
if (buttonPress || (url && $(window).scrollTop() > $(document).height() - $(window).height() - 60)) {
// TODO - Removing this line was causing duplicates to load so it's worth investigating the cause
$('.pagination').html('Please Wait...');
return $.getScript(url);
}
};
if ($('#infinite-scrolling').length) {
console.log('if statement true');
$(window).scroll(function() {
console.log('window scroll');
paginate(false);
});
return $(window).scroll();
}
$('#infinite-scrolling-button').on('click', function() {
$(this).html('Loading...');
paginate(true);
$(this).html('Load more');
});
}
编辑:部分问题可能与涡轮链接有关。当我刷新页面时,滚动处理程序似乎不再触发。
当您希望页面自动滚动时,窗口滚动事件侦听器正在设置,但是当页面由于涡轮链接的行为而更改时,它不会取消设置。尝试使用 $(window).unbind("scroll");
在加载新页面时删除滚动事件。