Ruby on rails 4.0 + javascript无法加载

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