我正在尝试使用will_paginate
gem向我的rails应用程序添加无限滚动,然后使用AJAX获取下一个分页页面,但我的javascript未呈现。
似乎turbolinks导致了这个问题。当我删除turbolinks时,错误消失,但脚本不再运行。以下是我的日志和脚本。任何人都可以帮助我吗?
这是我从日志中得到的错误:
ActionView::Template::Error (SyntaxError: [stdin]:5:2: unexpected if):
5: <!-- had to add the script to override JS error -->
6: <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
7: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
8: <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
9: <%= csrf_meta_tags %>
10: </head>
11: <body>
app/views/layouts/application.html.erb:8:in `_app_views_layouts_application_html_erb___2390735874352053488_70114430886900'
我的links.js.coffee
jQuery ->
$(window).scroll ->
console.log('working')
if $(window).scrollTop() > $(document).height() - $(window).height() - 50
alert('next page')
现在,如果我取出脚本的一部分,将滚动位置与文档高度和窗口高度进行比较,则代码可以正常工作。
jQuery ->
$(window).scroll ->
console.log('working')
如果您需要查看任何其他信息,我很乐意提供。
答案 0 :(得分:1)
它看起来像缩进问题。 Coffeescript是空白敏感的。尝试
id
这里的差异是
jQuery ->
$(window).scroll ->
if $(window).scrollTop() > ($(document).height() - $(window).height() - 50)
alert('next page')
方法调用scroll
onReady函数。jQuery
alert
至于turbolinks问题,您不能简单地使用if
(onReady快捷方式)来加载所有内容。您可能需要添加另一个侦听器。
所以而不是:
jQuery ->
您可以尝试这样的事情:
jQuery ->
$(window).scroll ->
...
非常类似于此处所述:Rails 4: how to use $(document).ready() with turbo-links
希望这有帮助。