简体   繁体   English

jQuery-未捕获的TypeError:$不是函数

[英]jQuery - Uncaught TypeError: $ is not a function

I am so confused...I was working on my site and added some jQuery. 我很困惑...我正在我的网站上工作,并添加了一些jQuery。 Upon testing, I found that the jQuery didn't do anything. 经过测试,我发现jQuery没有执行任何操作。 I then tried the most simple yet visible code I could think of: 然后,我尝试了我能想到的最简单但可见的代码:

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

but that didn't do anything either. 但这也不起作用。 So I tried that same code in the js console and got back this error: 所以我在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)

and just entering $ just gives back "undefined". 而只输入$只会返回“ undefined”。

I investigated and found that I had accidentally moved my Gemfile, and that maybe the server couldn't access the jquery-rails gem. 我调查后发现,我不小心移动了Gemfile,并且服务器可能无法访问jquery-rails gem。 But after I moved it back and restarted the server, the problem didn't go away. 但是在我将其移回并重新启动服务器后,问题并没有解决。

Then I thought maybe I had some faulty code on my page that was preventing the jQuery from running. 然后我想也许页面上有一些错误的代码阻止了jQuery的运行。 I removed all the code so it was a just a blank document, ran it, and tried again, but I got the same errors in the console. 我删除了所有代码,因此它只是一个空白文档,运行并再次尝试,但是在控制台中出现了相同的错误。

The head of my app includes this: 我的应用程序的head人包括:

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

My app/assets/javascripts/application.js includes the line //= require jquery 我的app/assets/javascripts/application.js包含以下行//= require jquery

And bundle install returns "jquery-rails 4.1.1". 并且bundle install返回“ jquery-rails 4.1.1”。

I've ran plenty of jQuery before on the same page with no issues. 在同一页面上,我之前运行过很多jQuery,都没有问题。 It seems my server suddenly just stopped understanding jQuery. 看来我的服务器突然停止了解jQuery。 What on earth could be going on? 到底是怎么回事?

Wrap it in a jQuery function, like this: 将其包装在jQuery函数中,如下所示:

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

  $("html").click(function() {
     $("html").html("");
  });

});

Make sure you include jquery in app/assets/application.js : 确保在app/assets/application.js包含jquery:

//= require jquery
//= require jquery_ujs

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

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