当我在Rails中使用link_to帮助器时,加载我的javascript时遇到了一些问题.当我使用‘localhost:3000/products/new’手动输入url或重新加载页面时,javascript会加载,但当我通过如下所述的链接时,jQuery $(document).ready将不会加载到新页面上.

Link_to, javascript does not load when I click this link:

<%= link_to "New Product", new_product_path %>

products.js file

$(document).ready(function() {
    alert("test");
});

Any help would be much appreciated. Thanks in advance!

推荐答案

你在用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); 

Jquery相关问答推荐

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

我需要在上一个表格单元格中显示计算结果

jQuery .append() 创建两个元素而不是一个

可以推迟 jQuery 的加载吗?

更改高亮 colored颜色

Javascript 仅打印 iframe 内容

如何在 bootstrap 模式关闭并重新打开时重置 bootstrap 模式?

清除并刷新 jQuery Chosen 下拉列表

如何设置缓存:jQuery.get 调用中的 false

如何使用 jQuery 或 JavaScript 模拟单击​​按钮的动作?

Zepto 和 jQuery 2 有什么区别?

你如何获得文本区域中的光标位置?

如何使所有浏览器都支持 ?有什么 Select 吗?

所有选中复选框的 jQuery 数组(按类)

jquery变量语法

使用 jQuery 获取选定的选项 id

如何在 Angular 4 中使用 jQuery 插件?

隐藏 div 但保留空白

测试空 jQuery Select 结果

如何通过jQuery函数仅获取直接子元素