JQuery中事件冒泡

定义

在一个对象上触发某类事件,就会执行此事件程序,如果没有处理事件就会向这个对象的父级对象传播 直至它被处理,最顶层老大为document对象。

作用

事件冒泡允许多个操作被集中处理(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子级元素上)

阻止事件气泡

事件气泡有时是不需要的 通过event.stopPropagation() 或者event.preventDefault()组织 ----合并写法:return false;

解决思路

假如页面中有一个模块1,模块1中有又一个模块2,模块2中有个模块3,如果点击模块3中的触发事件,如没有处理程序,他就会向模块2执行,模块2没有继续向模块1执行,此为一个冒泡事件,如果想在模块3就终止需要---return false

具体实例代码

 <!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>

易错点

return false 写在函数内部

 

posted on 2018-05-09 22:17  大可可  阅读(128)  评论(0编辑  收藏  举报