Jquery not working inside html file

I am trying to make a very simple jQuery tutorial, but I cannot get it to work. I am calling the jquery library from google and then trying to create a script inside html.

If I do the same in the .js file, I will not have any problems. What am I missing here?

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
            $(document).ready(function() {
                $("a").click(function() {
                    alert("Hello world!");
                });
            });
        </script>
            <a href="">Link</a>

    </body>
</html>
+3
source share
2 answers

You need to break it down:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
    $(document).ready(function() {
        $("a").click(function() {
            alert("Hello world!");
        });
    });
</script>

... into two script elements:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("a").click(function() {
            alert("Hello world!");
        });
    });
</script>

In the passage you indicated, the code in the element <script>will not be evaluated, because the browser only evaluates the content from the attribute srcand ignores everything else.

+10
source

Move your scripts to the head element as follows:

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("a").click(function () {
                alert("Hello world!");
            }); 
        });
    </script>
</head>
<body>    
    <a href="#">Link</a>
</body>
</html>
+1
source

Source: https://habr.com/ru/post/1792985/


All Articles