你在用Rails 4吗?(在您的控制台中执行rails -v
以了解情况)
This issue is probably due to the newly added Turbolinks gem. It makes your application behave like a single page JavaScript application. It has a few benefits (it's faster), but it unfortunately breaks some existing events like $(document).ready()
because the page is never reloaded. That would explain why the JavaScript works when you directly load the URL, but not when you navigate to it through a link_to
.
这是关于Turbolinks的RailsCast分.
有几个解决方案.您可以使用jquery.turbolinks作为下拉修复,也可以将$(document).ready()
语句切换为使用Turbolinks 'page:change'
事件:
$(document).on('page:change', function() {
// your stuff here
});
Alternatively, you could do something like this for compatibility with regular page loads as well as Turbolinks:
var ready = function() {
// do stuff here.
};
$(document).ready(ready);
$(document).on('page:change', ready);
If you are using Ruby on Rails >5 (you can check by running rails -v
in the console) use 'turbolinks:load'
instead of 'page:change'
$(document).on('turbolinks:load', ready);