简体   繁体   中英

understanding javascript/jquery events: why does this alert fire four times?

I have basic feel for using javascript and jquery and want to understand what exactly is going on when an event fires.

This code generates FOUR alerts that say "submitButton." Why is that?

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Demo</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
               $(document).ready(function () {
                         $("*").click(function(event) {
                            alert(event.target.id);
                        });
               });
        </script>

    <body>


        <div id='submitDiv'>
        <input id='submitButton' type="submit" class="button" value="Submit"/>
        </div>

    </body>
</html>

The * literal selects all elements. So you're adding a handler to:

  1. document (html)
  2. body
  3. submitDiv
  4. submitButton

Note that events bubble (bottom up to the top of the DOM). You can prevent the event bubbling by returning false from a handler:

$("*").click(function(event) {
    alert(event.target.id);
    return false;
});

Fiddle

Your code attaches a click handler to all elements and because the event propagates up, it will hit all click handlers from <input> all the way up to document .

why does the alert say "submitButton" four times?

This is because you're referencing event.target which always points to the first clicked element. If you want to show a different id for each element in the propagation you need to reference this , ie:

alert(this.id);

You can stop propagation by either returning false from your click handler or explicitly via the event object:

$('*').on('click', function(event) {
    event.stopPropagation();
    alert(event.target.id);
});

This is not recommended though, because having all those event handlers take up memory. It would be better to use event delegation.

jQuery(function($) {
    $(document).on('click', function(event) {
        console.log(event.target);
    });
});

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