javascript跨浏览器事件

javascript跨浏览器事件

<html>
 <head></head>
 <body>
  <div id="div1">1111111111
   <div id="div2">2222222222</div>
  </div>
  <script type="text/javascript">
     var EventUtil = {
    addHandler:function(element,type,handler){
     if(element.addEventListener){
      element.addEventListener(type,handler,false);
     }else if(element.attachEvent){
      element.attachEvent('on'+type,handler);
     }else {
      element['on'+type]=handler;
     }
    },
    removeHandler:function(element,type,handler){
     if(element.addEventListener){
      element.removeEventListener(type,handler,false);
     }else if(element.attachEvent){
      element.detachEvent('on'+type,handler);
     }else {
      element['on'+type]=null;
     }
    }
     }
  
   function alertid(){
    alert(this.id);
   }
   var div1 = document.getElementById('div1');
   var div2 = document.getElementById('div2');
   EventUtil.addHandler(div2,'click',alertid);
   //EventUtil.removeHandler(div2,'click',alertid);
   //ie
   //div1.attachEvent('onclick',alertid);
   //div2.attachEvent('onclick',alertid);
   
   //非ie
   //div1.addEventListener('click',alertid,true);
   //div2.addEventListener('click',alertid,true);
  </script>
 </body>
</html>

你可能感兴趣的:(javascript跨浏览器事件)