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条回答
荒废的爱情
2楼-- · 2018-12-31 07:33

This solution worked for me

;(function($){
    // your code
})(jQuery);

Move your code inside the closure and use $ instead of jQuery

I found the above solution in https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma

...after searching too much

查看更多
还给你的自由
3楼-- · 2018-12-31 07:33

Try this:

<script language="JavaScript" type="text/javascript" src="jquery/jquery.js"></script>
<script>
    jQuery.noConflict();
    (function ($) {
        function readyFn() {
            // Set your code here!!
        }

        $(document).ready(readyFn); 
    })(jQuery);

</script>
查看更多
柔情千种
4楼-- · 2018-12-31 07:33

replace $ sign with jQuery like this:

jQuery(function(){
//your code here
});
查看更多
与君花间醉酒
5楼-- · 2018-12-31 07:36

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...

查看更多
临风纵饮
6楼-- · 2018-12-31 07:37

You come across this issue when your function name and one of the id names in the file are same. just make sure all your id names in the file are unique.

查看更多
人间绝色
7楼-- · 2018-12-31 07:39
<script>
var jq=jQuery.noConflict();
(function ($) 
    {
    function nameoffunction()
    {
        // Set your code here!!
    }

    $(document).ready(readyFn); 
    })(jQuery);

now use jq in place of jQuery

查看更多
登录 后发表回答