简体   繁体   English

Ruby on Rails 4 javascript 未执行

[英]Ruby on Rails 4 javascript not executed

I have a custom js file in app/assets/javascripts .我在app/assets/javascripts有一个自定义js文件。 This is the js file:这是js文件:

//app/assets/javascripts/contacts.js
//$(document).ready(function() { //I've already tried with this method

$(window).load(function() {
    alert("foo bar")
});

I require the file contacts.js file in the application.js file.我需要application.js文件中的文件contacts.js文件。

If I inspect the html page I see the js file loaded correctly, but the message is not shown.如果我检查 html 页面,我会看到正确加载了 js 文件,但未显示消息。 If I reload the page (by pressing f5), the message is correctly show.如果我重新加载页面(按 f5),则消息会正确显示。

When the page is loaded the javascript is loaded (I can see it in source html code in the browser) but not executed.当页面加载时,javascript 被加载(我可以在浏览器的源 html 代码中看到它)但没有执行。

Can you help me?你能帮助我吗?

SOLUTION: Rails 4: how to use $(document).ready() with turbo-links解决方案: Rails 4:如何将 $(document).ready() 与 turbo-links 一起使用

$(document).ready(function() { } # Not working with turbo-links

From

Turbolinks overrides the normal page loading process, the event that this relies on will not be fired. Turbolinks 覆盖了正常的页面加载过程,它所依赖的事件不会被触发。 If you have code that looks like this, you must change your code to do this instead:如果您的代码看起来像这样,则必须更改代码以执行此操作:

$(document).on('ready page:load', function () {
  // you code here
});

Another question 另一个问题

With Turbolinks version 5 (starting from Rails 5) you need to use:对于 Turbolinks 版本 5(从 Rails 5 开始),您需要使用:

$(document).on("turbolinks:load", function () {
  // YOUR CODE
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM