简体   繁体   中英

Why does jQuery event fire when binding?

When the page loads, I get the message box saying "testing" even before I click on the button. Is this functionality normal? I have also tried .click and .on with the same results.

<script type="text/javascript">
    function Update() {
        alert("testing");
    }
    $(document).ready(function () {
        $("#UpdateButton").bind(Update())
    });
</script>

You aren't binding the function. You're calling the function and then binding the output of the function. Try clicking on your button and see if the event fires.

Instead, bind the function iteself (notice the lack of parentheses: () ):

$("#UpdateButton").on('click', Update)

Or:

$("#UpdateButton").click(Update)

You are calling this function here not binding it to a click like you are thinking..which will when it is clicked..

$("#UpdateButton").bind(Update());

This is the click event

    $("#UpdateButton").bind('click', Update);
OR

$("#UpdateButton").live('click', Update);  // Deprecated

OR 

$("#UpdateButton").on('click', Update);  // Use this instead
$(document).ready(function () {
            $("#UpdateButton").click(function(){
Update();
});
    });

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