jQuery-Uncaught TypeError:$不是函数

jQuery - Uncaught TypeError: $ is not a function

本文关键字:函数 TypeError jQuery-Uncaught      更新时间:2024-04-26

我很困惑。。。我在我的网站上工作,添加了一些jQuery。经过测试,我发现jQuery什么都没做。然后我尝试了我能想到的最简单但可见的代码:

<script type="text/javascript">
  $("html").click(function() {
    $("html").html("");
  });
</script>

但这也没什么作用。所以我在js控制台中尝试了同样的代码,结果返回了这个错误:

Uncaught TypeError: $ is not a function
  at <anonymous>:2:1
  at Object.InjectedScript._evaluateOn (<anonymous>:848:140)
  at Object.InjectedScript._evaluateAndWrap (<anonymous>:891:34)
  at Object.InjectedScript.evaluate (<anonymous>:627:21)

而仅仅输入CCD_ 1就返回"未定义"。

我调查了一下,发现我不小心移动了我的Gemfile,可能服务器无法访问jquery-rails gem。但在我将其移回并重新启动服务器后,问题并没有消失。

然后我想我的页面上可能有一些错误的代码,导致jQuery无法运行。我删除了所有的代码,所以它只是一个空白文档,运行了它,然后重试,但我在控制台中遇到了同样的错误。

我的应用程序的head包括以下内容:

<head>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
</head>

我的app/assets/javascripts/application.js包括线路//= require jquery

bundle install返回"jquery rails 4.1.1"。

我以前在同一个页面上运行过很多jQuery,没有任何问题。我的服务器似乎突然停止了对jQuery的理解。到底会发生什么?

将其封装在jQuery函数中,如下所示:

// Note the "$" inside function() - that's the key
jQuery( document ).ready(function( $ ) {
  $("html").click(function() {
     $("html").html("");
  });
});

确保在app/assets/application.js:中包含jquery

//= require jquery
//= require jquery_ujs