js事件冒泡、阻止事件冒泡以及阻止默认行为

事件冒泡

当事件发生后,这个事件就要开始传播(从里到外或者从外向里)。为什么要传播呢?因为事件源本身(可能)并没有处理事件的能力,即处理事件的函数(方法)并未绑定在该事件源上。例如我们点击一个按钮时,就会产生一个click事件,但这个按钮本身可能不能处理这个事件,事件必须从这个按钮传播出去,从而到达能够处理这个事件的代码中(例如我们给按钮的onclick属性赋一个函数的名字,就是让这个函数去处理该按钮的click事件),或者按钮的父级绑定有事件函数,当该点击事件发生在按钮上,按钮本身并无处理事件函数,则传播到父级去处理。

什么是事件冒泡

<!DOCTYPE html>
<html lang="en" onclick="alert('html')">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <title>Document</title>
</head>
<body onclick="alert('body')">
    <!--html-->
    <div style="width:400px; height:400px; background:red" onclick="alert(this.style.background)">
            <div id="div2" style="width:300px; height:300px; background:palevioletred">
                    <div style="width:200px; height:200px; background:yellow" onclick="alert(this.style.background)">
                            <div id="div1" style="width:100px; height:100px; background:palegreen">
                                <a id="aaa" href="http://www.baidu.com">aaa</a> 
                            </div>
                    </div>
            </div>
    </div>

    <script>
        //此jquery既阻止默认行为又停止冒泡
        // $("#div1").on('click',function(){
        //     return false;
        // });

        window.onload = function () {
            var oDiv1 = document.getElementById('div1');
            var oDiv2 = document.getElementById('div2');

            oDiv1.onclick = function (ev){
                var oEvent = ev || event;
                alert("this is div1");
                
                //js阻止事件冒泡
                //oEvent.cancelBubble = true;
                //oEvent.stopPropagation();

                //js阻止链接默认行为,没有停止冒泡
                //oEvent.preventDefault(); 
                //return false;
            }

            oDiv2.onclick = function (ev){
                var oEvent = ev || event;
                alert("this is div2");
                oEvent.cancelBubble = true; 
            }
        }
    </script>
</body>
</html>

 

 

 

posted @ 2017-10-17 15:32  jsanntq  阅读(109913)  评论(0编辑  收藏  举报