【发布时间】:2016-07-31 02:02:27
【问题描述】:
在过去的 8 小时里,我一直试图让这个无限滚动脚本正常工作,但无法弄清楚。
我在这里上传了网站,所以你可以看到问题:http://kevinellerton.com/meditationmagazine/article01/ 当你向下滚动时,它应该加载 article04,然后是 03,然后是 02,然后停止加载文章,因为 article01 已经加载了。问题是它不会停止加载它们......如果你在控制台中跟踪控制台记录的变量,那真的很不稳定。我认为问题可能与“范围”有关,但我不确定:-(
如果可以的话请帮忙!
非常感谢!
$(document).ready(function() {
// DATABASE OF ARTICLES
var database = [
"article04",
"article03",
"article02",
"article01"
];
// THIS WHOLE SECTION CREATES THE INFINITE SCROLL EFFECT BY ACCESSING THE ARTICLES IN ORDER.
// IT'S NOT QUITE WORKING THOUGH.
// IF YOU FIGURE OUT THE BUGS, YOU CAN ACTIVATE INFINITE SCROLL!
// POST CODE ON STACKOVERFLOW... MAYBE YOU'LL GET SOME HELP!
// get initial page name
if (articleCounter == 0) {
var pathArray = window.location.pathname.split('/');
var pageName = pathArray[2];
console.log(pageName);
}
// initialize variables
var win = $(window);
var articleCounter = 0;
console.log(articleCounter);
// Each time the user scrolls
win.scroll(function() {
// End of the document reached?
if ($(document).height() - win.height() == win.scrollTop()) {
$('#loading').show();
// if this article is the next one in the list, skip it and go to next one
if (pageName == database[articleCounter]) {
articleCounter++;
var nextPage = database[articleCounter];
pageName = nextPage;
console.log(nextPage);
} else {
var nextPage = database[articleCounter];
pageName = nextPage;
console.log(nextPage);
}
// append nextPage to the end of the document
if (nextPage !== undefined) {
$.ajax({
url: '../' + nextPage + '/index.php',
dataType: 'html',
success: function(html) {
$('body').append(html);
$('#loading').hide();
articleCounter++;
console.log(articleCounter);
// POSSIBLE TO CHANGE URL PATH NAME HERE???
}
});
}
}
});
});
编辑:
我今天完全重写了它,但仍然存在完全相同的问题。我 90% 确定问题与 SCOPE 有关,但我并没有完全弄清楚。这是我的新代码,但仍然无法正常工作:
$(document).ready(function() {
// DATABASE OF ARTICLES
var database = [
"article04",
"article03",
"article02",
"article01"
];
var articleCounter = 0;
// get initial page name
var pathArray = window.location.pathname.split('/');
var initialPage = pathArray[2];
alert("Initial page is " + initialPage);
// when you scroll
$(window).scroll(function() {
// if you've reached the end of the document
if ($(document).height() - $(window).height() == $(window).scrollTop()) {
$('#loading').show();
// if you've reached the end of the database
if (articleCounter >= database.length) {
// load ending footer
alert("You've reached end of database! articleCounter is " + articleCounter);
// quit program
}
else if (database[articleCounter] == initialPage) {
articleCounter++;
appendArticle();
articleCounter++;
}
else {
appendArticle();
articleCounter++;
}
}
});
// end scroll function
function appendArticle() {
$.ajax({
url: '../' + database[articleCounter] + '/index.php',
dataType: 'html',
success: function(html) {
$('body').append(html);
$('#loading').hide();
// POSSIBLE TO CHANGE URL PATH NAME HERE???
}
});
}
【问题讨论】:
标签: javascript jquery scope infinite-scroll