通用事件绑定方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style type="text/css">
*{
    margin: 0;
    padding: 0;
}
body{
    margin: 100px;
}
</style>
</head>
<body>
<div id="box">
    <p id="p1">p1</p>
    <p id="p2">p2</p>
    <p id="p3">p3</p>
    <a href="http://baidu.com" id="a1">a1</a>
    <a href="http://baidu.com" id="a2">a2</a>
    <a href="http://baidu.com" id="a3">a3</a>
</div>
</body>
</html>
<script type="text/javascript">
var box = document.getElementById("box");
addEvent(box,"click","a",function(e){
    e.preventDefault();
    console.log(123);
});
var p2 = document.getElementById("p2");
addEvent(p2,"click",function(e){
    e.preventDefault();
    console.log(e.target);
});
function addEvent(el,type,selector,fn){
    if(fn==null){
        fn = selector;
        selector = null;
    }
    el.addEventListener(type,function(e){
        var target;
        if(selector){
            // 代理
            target = e.target;
            if(target.matches(selector)){
                fn.call(target,e)
            }
        } else {
            // 不代理
            fn(e);
        }
    });
}
</script>

 

posted on 2017-12-02 19:29  jasonduanmu  阅读(140)  评论(0编辑  收藏  举报

导航