【问题标题】:jQuery $(document).ready is not a function - Rails 3.1jQuery $(document).ready 不是一个函数 - Rails 3.1
【发布时间】:2011-10-04 00:30:54
【问题描述】:

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

<div id="myDiv">
  here is some content here
</div>

当我打电话时:

$(document).ready(function() {
  $("#myDiv").hide();
})

我的浏览器报错

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

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

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

我的浏览器报错

$("#myDiv") is null @ http://localhost:3000/:57

这是有趣的部分。当我删除 # 并像这样写时

$("myDiv").hide();

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

$("myDiv").addClass is not a function @ http://localhost:3000/:57

我没有其他 javascript 错误。知道为什么会发生这种情况吗?我该如何解决这个问题?

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

这是我的 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();
})

顺便说一句,我尝试删除所有引导 js 文件,但没有任何影响。显然是在加载 jQuery。

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

【问题讨论】:

  • 您确定包含 jquery 的脚本标签在您使用之前出现在最终标记中吗?

标签: jquery ruby-on-rails ruby-on-rails-3 jquery-selectors ruby-on-rails-3.1


【解决方案1】:

如果您有意同时使用 jquery 和原型,则需要 noConflict 其中之一;你在 jQuery 之后加载原型,所以重新定义 $ 函数。

【讨论】:

  • 啊!感谢您及时的回复。我刚刚删除了 Prototype 并修复了它。我不知道为什么那条线在那里!
  • @alik 魔法!一直在发生:)
  • 仅供可能搜索并到达这里的人使用,如果在 jQuery 上启用 noConflict,则必须将每个 $ 更改为 jQuery,因此 jQuery(document).ready(...
猜你喜欢
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多