简体   繁体   中英

jQuery click event not working

The below code works well on localhost using XAMPP. But it doesn't work on another server.

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery-latest.js"></script>
    </head>
    <body>
        word: <input type="text" id="sub" />
        user: <input type="text" id="user" />

        <button type="button" id="btn">Click Me!</button>

        <script>
            $("#btn").click(function () {
                var word=$("#sub").val();
                var usr=$("#user").val();
                alert("hi");
            });
        </script>
    </body>
</html>

I have got 2 errors from Chrome inspect element:

  • Uncaught SyntaxError: Unexpected end of input jquery-latest.js:5669

  • Uncaught ReferenceError: $ is not defined

check jquery-latest.js is same directory with html file. Otherwise code is ok and also works. add type in the script. try this

<script type="text/javascript" src="jquery-latest.js"></script>

You need to wire up the click handler in the $(document).ready() event.

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery-latest.js"></script>
        <script>
        $(document).ready(function() {
            $("#btn").click(function () {
                var word=$("#sub").val();
                var usr=$("#user").val();
                alert("hi");
            });
        });
        </script>
    </head>
    <body>
        word: <input type="text" id="sub" />
        user: <input type="text" id="user" />

        <button type="button" id="btn">Click Me!</button>
    </body>
</html>

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