TypeError: $ is not a function when calling jQuery

2018-12-31 07:05发布

I have a simple jQuery script in a WordPress plugin that is using a jQuery wrapper like this:

$(document).ready(function(){

    // jQuery code is in here

});

I am calling this script from within the WordPress Dashboard and am loading it AFTER the jQuery framework has loaded.

When I check the page in Firebug I constantly keep receiving the error message:

TypeError: $ is not a function

$(document).ready(function(){

Should I maybe wrap the script in this function:

(function($){

    // jQuery code is in here

})(jQuery);

I have had this error quite a few times and am not sure how to handle it.

Any help would be greatly appreciated.

15条回答
伤终究还是伤i
2楼-- · 2018-12-31 07:40
(function( $ ) {
  "use strict";

  $(function() {

    //Your code here

  });

}(jQuery));
查看更多
有味是清欢
3楼-- · 2018-12-31 07:43

Use

jQuery(document).

instead of

$(document).

or

Within the function, $ points to jQuery as you would expect

(function ($) {
   $(document).
}(jQuery));
查看更多
墨雨无痕
4楼-- · 2018-12-31 07:45

What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>
查看更多
心情的温度
5楼-- · 2018-12-31 07:49

By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries).

Your solution of wrapping it in function will work fine, or you can load jQuery some other way (but that's probably not a good idea in Wordpress).

If you must use document.ready, you can actually pass $ into the function call:

jQuery(function ($) { ...
查看更多
忆尘夕之涩
6楼-- · 2018-12-31 07:52
var $=jQuery.noConflict();

$(document).ready(function(){
    // jQuery code is in here
});

Credit to Ashwani Panwar and Cyssoo answer: https://stackoverflow.com/a/29341144/3010027

查看更多
公子世无双
7楼-- · 2018-12-31 07:52

Also, I find the good solution for use jQuery noConflict mode.

(function($){

  $(document).ready(function(){
      // write code here
  });

  // or also you can write jquery code like this

  jQuery(document).ready(function(){
      // write code here
  });

})(jQuery);

I found this solution from here. https://thecodingstuff.com/how-to-properly-use-jquery-noconflict-mode-in-wordpress/

查看更多
登录 后发表回答