javascript高级课程-1

绑定过个事件的难题

二级事件绑定

捕捉与冒泡

实测捕捉与冒泡

停止传播行为与阻止行为

绑定多个事件的难题:(用途:前端特效、服务端需要监看点击次数 因此两次绑定,仅仅后面的生效问题)

代码如下:

<a href="#" id="a" >a</a>
</body>
<script type="text/javascript">
    var a = document.getElementById("a");
    a.onclick=function(){
        alert("aa");
    }
    a.onclick=function(){
        alert("bb");
    }
</script>

最终弹出bb这是因为覆盖掉前面的onclick属性的值

高级绑定事件

a.addEventListener('click',function(){
        alert("aa");
    })
    a.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("bb");
    })
    a.removeEventListener('click',function(){//删除事件 第一个参数是事件 第二个是某个事件的某个值
        alert("aa");
    });
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #china{
            width:500px;
            height:500px;
        }
        div{
            width:80%;
            height: 80%;
            border:1px solid red;
            margin:10%;
        }
    </style>
</head>
<body>
<div id="china">
    china
    <div id="a">
        a
        <div id="b">
            b
        </div>
    </div>
</div>
</body>
<script type="text/javascript">
    var china = document.getElementById("china");
    var a = document.getElementById("a");
    var b = document.getElementById("b");
    a.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("b-a");
    },true);
    b.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("b-b");
    },true);
    china.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("b-china");
    },true);
    //冒泡
    a.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("m-a");
    });
    b.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("m-b");
    });
    china.addEventListener('click',function(){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("m-china");
    });
</script>
</html>

默认为捕捉过程

点击china b-china m-china

点击a  b-china b-a m-a m-china

点击b b-china b-a b-b m-b m-a m-china

阻止事件

将上面的a的点击冒泡事件改为

a.addEventListener('click',function(event){//第一个参数绑定的事件、第二个参数为函数 、第三个是冒泡还是捕捉
        alert("m-a");
        event.stopPropagation();
    });

此时点击a b-china b-a m-a 

原文地址:https://www.cnblogs.com/webcyh/p/11386819.html