Rails,通过link_to helper点击后没有加载javascript [英] Rails, javascript not loading after clicking through link_to helper

查看:26
本文介绍了Rails,通过link_to helper点击后没有加载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() 因为页面永远不会重新加载.这将解释为什么当您直接加载 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 '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); 

这篇关于Rails,通过link_to helper点击后没有加载javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆