Event Bubbling in JQuery

Event Bubbling in JQuery

definition

When a certain type of event is triggered on an object, the event program will be executed. If the event is not processed, it will be propagated to the parent object of the object until it is processed, and the top-level boss is the document object.

effect

Event bubbling allows multiple operations to be handled centrally (add event handlers to a parent element, avoid adding event handlers to multiple child elements)

Block event bubbles

Event bubbles are sometimes not needed to organize through event.stopPropagation() or event.preventDefault() ---- combined writing: return false;

Solutions

If there is a module 1 in the page, another module 2 in module 1, and a module 3 in module 2, if the trigger event in module 3 is clicked, if there is no handler, it will be executed to module 2, and module 2 does not Continue to execute to module 1, this is a bubbling event, if you want to terminate in module 3, you need ---return false

specific example code

 <!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .father {width: 500px;height: 500px;background: pink;}
            .son {width: 250px;height: 250px;background: red; }
            .grandson {width: 150px;height: 150px; background: gold;}
        </style>
        <script type="text/javascript" src="js/jquery-1.12.4.min.js" ></script>
        <script>
                $(function(){
                            var $box1 = $('.father');
                        var $box2 = $('.son');
                           var $ box3 = $ ('. grandson');
                        $box1.click(function() {
                            alert('father');
                                });
                                
                        $box2.click(function() {
                               alert('son'); return false;
                                });
                                
                        $box3.click(function(event) {
                               alert('grandson');
                            return false;
                                });
//                         $(document).click(function(event) {
//                          alert('grandfather');
//                              });
                             })    
        </script>
    </head>
    <body>
        <div class="father">
            <div class="son">
                <div class="grandson"></div>
    </div>
</div>
    </body>
</html>

error prone

return false is written inside the function

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326663858&siteId=291194637