jQuery $(document).ready不是函数 - Rails 3.1

ali*_*lik 1 jquery ruby-on-rails jquery-selectors ruby-on-rails-3 ruby-on-rails-3.1

我对rails很新,最近将rails 3.0应用程序升级到rails 3.1.事情似乎工作正常,但是当我开始在我的应用程序中编写一些jquery时,我无法调用大多数jquery方法.例如,我有一个div:

<div id="myDiv">
  here is some content here
</div>
Run Code Online (Sandbox Code Playgroud)

我打电话的时候:

$(document).ready(function() {
  $("#myDiv").hide();
})
Run Code Online (Sandbox Code Playgroud)

我的浏览器抛出错误

$(document).ready is not a function @ http://localhost:3000/assets/application.js?body=1:11
Run Code Online (Sandbox Code Playgroud)

需要注意的是,当我在div下面编写没有$(document).ready()的js时,就像这样

<div id="myDiv">
    here is some content
</div>
<script type="text/javascript" charset="utf-8">
    $("#myDiv").hide();
</script>
Run Code Online (Sandbox Code Playgroud)

我的浏览器抛出错误

$("#myDiv") is null @ http://localhost:3000/:57
Run Code Online (Sandbox Code Playgroud)

这是有趣的部分.当我删除#并写出来的时候

$("myDiv").hide();
Run Code Online (Sandbox Code Playgroud)

有用!!没有错误.为什么?我不知道.但是当我把它改成$("myDiv").addClass("anotherClass"); 或任何花哨的东西,我再次得到错误

$("myDiv").addClass is not a function @ http://localhost:3000/:57
Run Code Online (Sandbox Code Playgroud)

我没有其他javascript错误.知道为什么会这样吗?我怎样才能解决这个问题?

我已经gem 'jquery-rails'在我的gem文件中添加了.

这是我的application.js文件

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file. // require_tree 
//
//= require jquery
//= require jquery_ujs
//= require prototype
//= require bootstrap-alerts-1.3.0
//= require bootstrap-dropdown-1.3.0
//= require bootstrap-modal-1.3.0
//= require bootstrap-twipsy-1.3.0
//= require bootstrap-popover-1.3.0
//= require bootstrap-scrollspy-1.3.0
//= require bootstrap-tabs-1.3.0

$(document).ready(function() {
  $("#myDiv").hide();
})
Run Code Online (Sandbox Code Playgroud)

我尝试删除btw的所有bootstrap js文件,没有任何影响.它显然正在加载jQuery.

关于如何让jQuery正常工作的任何线索?

Dav*_*ton 7

如果你故意同时使用jquery和prototype,你需要noConflict中的一个; 你在jQuery之后加载原型,所以重新定义$函数.

  • 对于可能会搜索并到达此处的人,如果在jQuery上启用noConflict,则必须将每个$更改为jQuery,因此jQuery(document).ready(... (3认同)