jQuery onclick does not work

前端 未结 4 575
梦如初夏
梦如初夏 2021-01-23 12:25

I trying to get onclick work, but it does not... Here is my code:

HTML




        
相关标签:
4条回答
  • 2021-01-23 12:46

    You need to wait for the document to be ready. You are attempting to attach a click event on something the page does know exists yet.

    Fixes range from:

    1. moving your the script block to the bottom of the page.
    2. or using jQuery's document ready e.g. $(document).ready(function () { ... }); or $(function() { ... });

    Of course I'd start with justifying the use of jQuery if all you're using it for is to attach and event listener, but that's just me.

    Good luck

    0 讨论(0)
  • 2021-01-23 12:47

    While the accepted answer (using ready) works, it's not best practice.

    Best practice is to put your script tags at the end of the document, just before the closing </body> tag, note the comments below:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
    <head>
        <title>jQuery alert test</title>
        <meta charset="utf-8" />
    
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">        
        <!-- NO SCRIPTS HERE -->
    </head>
    <body>
        <div class="container">
            <div class="text-center">
                <a class="btn btn-primary" id="submit">Submit</a>
            </div>
        </div>
    
        <!-- SCRIPTS GO HERE -->
        <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
        <script>
            $('#submit').click(function(){
                alert('This onclick function forks!');
            });
        </script>
    </body>
    </html>
    

    That way

    1. The elements exist when your code runs

    2. Downloading the external scripts doesn't hold up the display of your page

    More in the YUI Best Practices for Speeding Up Your Web Site.

    0 讨论(0)
  • 2021-01-23 12:52

    Your JS is being exucuted before the DOM elements have loaded. Your event handler is therefore not being attached to the element since it doesn't exist at the time.

    Wrap your JS with a DOM ready handler:

    $(document).ready(function () {
        $('#submit').click(function(){
            alert('This onclick function forks!');
        });
    });
    

    You could also just use event delegation since the document object exists at the time of execution:

    $(document).on('click', '#submit', function () {
        alert('This onclick function forks!');
    });
    
    0 讨论(0)
  • 2021-01-23 12:53

    Maybe JQuery library is missing..then add this on you code:

    $(document).ready(function(){
    ...code here..
    });
    
    0 讨论(0)
提交回复
热议问题