我提到了http://railscasts.com/episodes/114-endless-page?autoplay=true在我的项目中利用无限滚动。在视频中他提到的所有内容我猜都是旧的,所以我尝试将其修改为 Rails 4。javascript 文件是
var currentPage = 1;
function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
new Ajax.Request('/shirts/first?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get'});
} else {
setTimeout("checkScroll()", 250);
}
}
function nearBottomOfPage() {
return scrollDistanceFromBottom() < 150;
}
function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
document.observe('dom:loaded', checkScroll);
我没有使用 rjs 文件,而是在 .js.erb 中编写了以下代码
if @first.total_pages > @first.current_page
page.call 'checkScroll'
else
page['#loading'].hide
end
我做事正确吗?当我用 firebug 检查浏览器时,它显示:
TypeError: document.observe is not a function
document.observe('dom:loaded', checkScroll);
我的代码有什么问题吗?有人可以帮我解决这个问题吗?
最佳答案
我认为railscast示例使用prototype.js而不是 jQuery,我猜您在 Rails 4 应用程序中使用 jQuery,因为我认为 document.observe
是 method in prototype ,不在 jQuery 中。
您可能想查看 revised episode for endless scrolling ,不幸的是它不是免费的,但来自 Railscast 的 Ryan Bates 也在 github 上分享了他的代码,这样你就可以看到修改后的剧集的 code on github ,这是 Rails 3.1 并使用 jQuery,因此可能更容易移植到 Rails 4。
希望这有帮助。
关于javascript - 在 rails 上无限滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21528274/