javascript模拟jQuery封装委托事件,兼容IE

时间:2022-12-01 18:45:58
 
 
 1 var $ = function(id){
 2             var dom = document.getElementById(id);
 3             return {
 4                 on:function(eventType,element,callback){
 5                     if(document.addEventListener){
 6                         dom.addEventListener(eventType,function(e){
 7                             var ev = e || window.event;
 8                             var target = ev.target || ev.srcElement
 9                             if(target.tagName.toLowerCase()===element){
10                                 callback.call(target,ev);
11                             }
12                         },false);    
13                     }else{
14                         //兼容IE浏览器
15                         document.attachEvent("on"+eventType,function(e){
16                             var ev = e || window.event;
17                             var target = ev.target || ev.srcElement
18                             if(target.tagName.toLowerCase()===element){
19                                 callback.call(target,ev);
20                             }
21                         });
22                     }
23                 }
24             }
25         };