简体   繁体   中英

“Uncaught ReferenceError: $ is not defined” vs. another error

<script type="text/javascript" href="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="/stylesheets/style.css">

At the end of the page, there are the following scripts:

Case 1: no error, but "hello" was not printed out on console

<script>
(function() {
     console.log("hello");
});
</script>

Case 2: I got an error: "Uncaught ReferenceError: $ is not defined"

<script>
$(document).ready(function() {
     console.log("hello");
});
</script>

Can you tell me why I got these errors and how I can fix them? Thanks

您必须在<script>标记中使用src而不是href

Case 1: You're defining the function, but never calling it. You need to put a pair of parentheses after the expression:

(function() {
     console.log("hello");
})();

Case 2: The correct syntax for <script> tags is src=URL , not href=URL .

change href to src

In js we use src and in css we use href

 <script type="text/javascript" href="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

change to

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

1) Maybe you are calling your jquery script before loading the jQuery library.

2) Load your jquery script with src instead of href in the <script> tag. Maybe you are not loading jquery on your page, try checking if there are any failed to load resource errors on your console..hope this helps

3) To know if jquery is working in your website for sure, try this but i hope the above two will solve the issue:

(function() {
    if (window.addEventListener) {
        // Standard
        window.addEventListener('load', jQueryCheck, false);
    }
    else if (window.attachEvent) {
        // Microsoft
        window.attachEvent('onload', jQueryCheck);
    }
    function jQueryCheck() {
        if (typeof jQuery === "undefined") {
            // No one's loaded it; either load it or do without
        }
    }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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