js中事件的绑定与解绑:attachEvent/detachEvent、addEventListener/removeEventListener

<!doctype html>
<html>
    <head>
        <!--声明当前页面编码集(中文编码<gbk,gb2312>,国际编码<utf-8>)-->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="keywords" content="关键词,关键词">
        <meta name="description" content="">
        <title> html </title>
        <style type="text/css">
            *{padding:0px;margin:0px;}
            #box1{width:400px;padding:50px;background:pink;}
            #box2{padding:50px;background:yellow;}
            #box3{padding:50px;background:red;}
        </style>
    </head>
<body>
    <div id="box1">
        <div id="box2">
            <div id="box3"></div>
        </div>
    </div>
    <script>
        /*
            事件的解绑
            attachEvent  ----> detachEvent
            addEventListener--> removeEventListener
        */
        var box1 = document.getElementById("box1");
        var box2 = document.getElementById("box2");
        var box3 = document.getElementById("box3");
        
        /*
        //box3.onclick = fn;
        box2.onclick = fn;
        box2.onclick = null;
        box2.attachEvent("onclick",fn);
        //box3.attachEvent("onclick",fn);
        box2.detachEvent("onclick",fn);
        function fn(){
            alert(1);
        };
        */
        
        box3.addEventListener("click",fn,false);
        box3.removeEventListener("click",fn,true);
        function fn(){
            alert(2);
        }
    </script>
</body>
</html>

 

posted on 2016-07-19 14:17  阡陌丶  阅读(421)  评论(0编辑  收藏  举报

导航