Rails 4:JQuery .ready不触发 [英] Rails 4: JQuery .ready Not Firing

查看:85
本文介绍了Rails 4:JQuery .ready不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我可能会错过一些基本的知识,但关于stackoverflow的解决方案似乎无法解决我的问题.我似乎无法在Rails 4应用程序中触发JQuery的.ready函数.

No solutions on stackoverflow seem to be working for my issue here, though I am likely missing something basic. I can't seem to get JQuery's .ready function to fire in my Rails 4 application.

我在custom.js中尝试了以下解决方案:

I have tried the following solutions in custom.js:

1.

$(document).on('ready page:load', function () {
  alert("hello, world")
});

2.

var ready;
ready = function() {

  alert("Hello, world!")
};

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

3.

$(function() {
  alert("Hello, world!")
});

4.

window.onload=function(){ alert("Hello, javascript onload!") };

我的application.js清单如下所示:

My application.js manifest looks like this:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require custom
//= require plugins
//= require turbolinks
//= require_self
//= require_tree .

我的gemfile看起来像这样:

My gemfile looks like this:

gem 'rails', '4.0.0'
gem 'jquery-rails'
gem 'jquery-turbolinks'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'bootstrap-sass', '2.0.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'faker', '1.0.1'
gem 'will_paginate', '3.0.3'
gem 'bootstrap-will_paginate', '0.0.6'
gem 'pg'
gem 'devise'

控制台日志显示:

 TypeError: $ is not a function application.js:22

生成的来源包括:

       <script src="/assets/jquery.js?body=1"></script>
<script src="/assets/jquery.turbolinks.js?body=1"></script>
<script src="/assets/jquery_ujs.js?body=1"></script>
<script src="/assets/custom.js?body=1"></script>
<script src="/assets/plugins.js?body=1"></script>
<script src="/assets/turbolinks.js?body=1"></script>
<script src="/assets/application.js?body=1"></script>

如果我将其放入custom.js,它将起作用:

If I put this into custom.js, it works:

  alert("Hello, world!");

谢谢您的帮助!

推荐答案

首先,我不建议将任何js代码添加到application.js,因为这是清单文件.只需创建一个新文件,例如core.js.coffee并尝试

First of all, I don't recommend adding any js code to application.js as that is a manifest file. Simply create a new file, for example, core.js.coffee and try

$ -> alert 'Hello World!'

Rails中的链轮将您的所有js/coffee文件放入生产中的压缩且缩小的单个文件中.

Sprockets in Rails takes all your js / coffee files and puts them into a compressed and minified single file in production.

这篇关于Rails 4:JQuery .ready不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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