Rails,点击通过link_to帮助后javascript没有加载 [英] Rails, javascript not loading after clicking through link_to helper
问题描述
当我在rails中使用link_to帮助程序时,我在加载我的javascript时遇到了一些问题。当我手动输入带有'localhost:3000 / products / new'的url或重新加载页面时,javascript会加载,但是当我通过下面写的链接时,jQuery $(文档)。 ready
将不会加载到新页面上。
I'm having some trouble loading my javascript when I use a link_to helper in rails. When I either manually enter the url with 'localhost:3000/products/new' or reload the page, the javascript loads, but when I go through a link as written below, the jQuery $(document).ready
will not load on the new page.
Link_to,当我点击此链接时,javascript无法加载:
Link_to, javascript does not load when I click this link:
<%= link_to "New Product", new_product_path %>
products.js file
products.js file
$(document).ready(function() {
alert("test");
});
我们非常感谢任何帮助。提前致谢!
Any help would be much appreciated. Thanks in advance!
推荐答案
您使用的是Rails 4吗? (通过在控制台中执行 rails -v
查找)
Are you using Rails 4? (Find out by doing rails -v
in your console)
此问题可能是由于新添加的< a href =https://github.com/rails/turbolinks/\"rel =noreferrer> Turbolinks gem。它使您的应用程序的行为类似于单页JavaScript应用程序。它有一些好处(它更快),但遗憾的是它打破了一些现有的事件,如 $(document).ready()
,因为页面永远不会重新加载。这可以解释为什么当你直接加载URL时JavaScript工作,但是当你通过 link_to
导航到它时不能。
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 。
Here's a RailsCast about Turbolinks.
有几种解决方案。您可以使用 jquery.turbolinks 作为插件修复,或者您可以切换 $(document).ready()
声明改为使用Turbolinks '页面:更改'
事件:
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:
$(document).on('page:change', function() {
// your stuff here
});
或者,您可以执行类似的操作以兼容常规页面加载以及Turbolinks:
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);
如果您使用Ruby on Rails> 5(您可以通过运行进行检查> rails -v
在控制台中)使用'turbolinks:load'
而不是'page:change'
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);
这篇关于Rails,点击通过link_to帮助后javascript没有加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!