Rails,单击link_to helper后未加载javascript

2022-01-31 00:00:00 ruby-on-rails jquery javascript

当我在 rails 中使用 link_to 帮助程序时,我在加载我的 javascript 时遇到了一些问题.当我使用 'localhost:3000/products/new' 手动输入 url 或重新加载页面时,javascript 会加载,但是当我通过如下所示的链接时,jQuery $(document).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 文件

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)

这个问题可能是由于新添加的 Turbolinks gem.它使您的应用程序表现得像一个单页 JavaScript 应用程序.它有一些好处(它更快),但不幸的是,它破坏了一些现有事件,例如 $(document).ready(),因为页面永远不会重新加载.这可以解释为什么 JavaScript 在您直接加载 URL 时有效,但在您通过 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 'page:change' 事件:

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' 而不是 '页面:更改'

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); 

相关文章