TypeError: $ is not a function when calling jQuery function

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.


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 ($) { ...

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...


你可以避免这样的冲突

var jq=jQuery.noConflict();
jq(document).ready(function(){  
  alert("Hi this will not conflict now");
  jq('selector').show();
});
链接地址: http://www.djcxy.com/p/63192.html

上一篇: Uncaught TypeError:无法读取未定义的属性'toLowerCase'

下一篇: TypeError:$在调用jQuery函数时不是函数