简体   繁体   中英

Execute jQuery function after clicking <button>

I am struggling with the following piece:

<script>
$('button').click(function(){
alert("button clicked");
});
</script>

<button type="button" class="button-save">Save</button>

I do not get an alert when I click the button. I tried targeting the class with the button, but that didn't help either. I am trying to execute some ajax (not in my example of course) when I click the Save button like in this answer, so I need to find when the user clicked the button.

Can anyone help?

You have to wait until your page is completely rendered to bind handlers, else the elements dont exist yet. You have two options, move your script tags to after your HTML has been rendered:

<button type="button" class="button-save">Save</button>

<script>
    $('button').click(function(){
        alert("button clicked");
    });
</script>

Or wrap your code in a DOM ready statement.

<script>
    $(document).ready(function() {
        $('button').click(function(){
            alert("button clicked");
        });
    });
</script>

<button type="button" class="button-save">Save</button>

add this line in the head section of your html page

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

and rewrite your code to:

$( document ).ready(function() {
   $('button').click(function(){
       alert("button clicked");
   });
});

You need to wrap your code like so:

$(document).ready( function() {
    // your code goes here
});

The above basically says, "Target the document and all its elements once it's loaded and ready to go. Then execute your code."

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