问答详情
源自:2-4 IE事件处理程序及跨浏览器解决

在我电脑上测试不通过,在chrome和ie8都是在dom0级

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title></title>
</head>
<body>
<div>
   <input type="button" id="btn3" value="按钮3">
</div>
<script>
   function showMsg(){
       alert('Hello world!');
   }
   //browser compatible
var eventUtil={
       //add handler
addHandler:function(element,type,handler){
           if(element.addEventListener){
               //dom2 level
element.addEventListener(type,handler,false);
           }else if(element.attachEvent){
               //ie
element.attachEvent('on'+type,handler);
           }else{
               //dom0 level
               //在js中所有用.连接属性的时候都可以用[],element.onclick === element['onclick']
element['on'+type] = handler;
           }
       },
       //remove handler
removeHandler:function(element,type,handler){
           if(element.removeEventListener){
               element.removeEventListener(type,handler,false);
           }else if(element.detachEvent){
               element.detachEvent('on'+type,handler);
           }else{
               element['on'+type] = null;
           }
       }
   };
   //call object
eventUtil.addHandler('btn3','click',showMsg);
   //eventUtil.removeHandler('btn3','click',showMsg);
</script>
</body>
</html>


提问者:凌晨4点 2014-12-14 16:31

个回答

  • 笨笨猫
    2015-01-12 00:02:49

    43行应该改为:eventUtil.addHandler(btn3,'click',showMsg);