原生写事件委托

 1 // ============ 简单的事件委托
 2 function delegateEvent(interfaceEle, selector, type, fn) {
 3     if(interfaceEle.addEventListener){
 4     interfaceEle.addEventListener(type, eventfn);
 5     }else{
 6     interfaceEle.attachEvent("on"+type, eventfn);
 7     }
 8      
 9     function eventfn(e){
10     var e = e || window.event;    
11     var target = e.target || e.srcElement;
12     if (matchSelector(target, selector)) {
13             if(fn) {
14                 fn.call(target, e);
15             }
16         }
17     }
18 }
19 /**
20  * only support #id, tagName, .className
21  * and it's simple single, no combination
22  */
23 function matchSelector(ele, selector) {
24     // if use id
25     if (selector.charAt(0) === "#") {
26         return ele.id === selector.slice(1);
27     }
28     // if use class
29     if (selector.charAt(0) === ".") {
30         return (" " + ele.className + " ").indexOf(" " + selector.slice(1) + " ") != -1;
31     }
32     // if use tagName
33     return ele.tagName.toLowerCase() === selector.toLowerCase();
34 }
35 //调用
36 var odiv = document.getElementById("oDiv");
37 delegateEvent(odiv,"a","click",function(){
38     alert("1");
39 })

原文地址:http://www.w3cmark.com/2016/439.html

posted @ 2016-08-11 16:05  凉城丶旧梦  阅读(150)  评论(0编辑  收藏  举报