Ruby on rails 4.0 + javascript 未加载 [英] Ruby on rails 4.0 + javascript not loading

查看:23
本文介绍了Ruby on rails 4.0 + javascript 未加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为front.js"的 javascript 文件,我像往常一样使用以下代码从application.js"加载:

//= 需要前面

在front.js"中,我有很多功能要在文档准备好时启动,如下所示:

$(document).ready(function() {$("#test").click(function(event){...});});

但问题是front.js"仅在我手动刷新页面(ctrl+r/f5)时加载,而不是在我从一个页面移动到另一个页面时加载,因此我的javascript代码无法按需要执行.也许这来自 turbolinks,我不知道如何处理这个问题.当我将脚本直接放在 html 文件中时,它可以工作,但绝对不是正确的做法.

有人可以帮我吗?

解决方案

您可以通过三种方式来做到这一点.

一个.您可以将 jquery 代码包装在一个函数中,然后在页面加载时调用该函数.如果您的功能已准备就绪,您可以执行以下操作:

$(document).ready(ready);$(document).on('page:load', ready);

B.您可以使用 jquery 的实时事件或on"事件:

$(document).on("click","#test",function(){//你的代码});

c.您可以使用 jquery-turbolinks gem,它将 Rails Turbolink 事件绑定到 document.ready 事件,以便您可以以通常的方式编写 jQuery.如需更多信息,请参阅此处

I have a javascript file called "front.js" i load from "application.js" like usual with this code:

//= require front

Inside "front.js",i have many functions i want to launch when the document is ready like this:

$(document).ready(function() {
  $("#test").click(function(event){
    ...
  });
});

But the problem is "front.js" is loaded only when i refresh the page manually (ctrl+r / f5 ) and not when i move from page to page, so my javascript code cannot be executed as wanted. Maybe this comes from turbolinks, i dont know how to handle this issue. When i put scripts directly in the html files, it works but it's definitely not the right thing to do.

Can anyone help me on this please ?

解决方案

There are three ways by which you can do it.

a. You can wrap your jquery code inside a function and then call that function on page load. If your function is ready then you can do:

$(document).ready(ready);
$(document).on('page:load', ready);

b. You can use jquery's live event or "on" event:

$(document).on("click","#test",function(){
 // your code
});

c. You can use the jquery-turbolinks gem which will bind the Rails Turbolink events to the document.ready events so you can write your jQuery in the usual way. For more information refer to here

这篇关于Ruby on rails 4.0 + javascript 未加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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