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

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

问题描述

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

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

//= require front

在front.js里面,我有很多我想要的功能在文档准备就绪时启动:

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){
    ...
  });
});

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

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.

有人可以帮我吗?

推荐答案

有三种方法可以做到。

a。您可以将jquery代码包装在函数中,然后在页面加载时调用该函数。如果你的功能准备就绪,你可以这样做:

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。您可以使用jquery的直播活动或开启活动:

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

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

c。您可以使用jquery-turbolinks gem将Rails Turbolink事件绑定到document.ready事件,这样您就可以按照常规方式编写jQuery。有关更多信息,请参阅此处

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天全站免登陆