Are you using Rails 4?
(您在使用Rails 4吗?)
(Find out by doing rails -v
in your console)((通过在控制台中使用rails -v
来查找))
This issue is probably due to the newly added Turbolinks gem.
(此问题可能是由于新添加的Turbolinks gem。)
It makes your application behave like a single page JavaScript application.(它使您的应用程序的行为类似于单页JavaScript应用程序。)
It has a few benefits ( it's faster ), but it unfortunately breaks some existing events like $(document).ready()
because the page is never reloaded.(它有一些好处( 速度更快 ),但不幸的是,由于从未重新加载页面,它破坏了一些现有事件,例如$(document).ready()
。)
That would explain why the JavaScript works when you directly load the URL, but not when you navigate to it through a link_to
.(这可以解释为什么当您直接加载URL而不是通过link_to
导航到JavaScript时JavaScript可以工作的原因。)
Here's a RailsCast about Turbolinks.
(这是有关Turbolinks的RailsCast 。)
There are a couple solutions.
(有几种解决方案。)
You can use jquery.turbolinks as a drop-in fix, or you can switch your $(document).ready()
statement to instead use the Turbolinks 'page:change'
event:(您可以使用jquery.turbolinks作为嵌入式修复程序,也可以切换$(document).ready()
语句以使用Turbolinks'page '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:
(另外,您可以执行以下操作以与常规页面加载以及Turbolink兼容:)
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'
(如果您使用的是Ruby on Rails> 5(可以通过在控制台中运行rails -v
进行检查),请使用'turbolinks:load'
而不是'page:change'
)
$(document).on('turbolinks:load', ready);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…