1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 </head> 7 <body> 8 <input type="username" id="username" /> 9 <script> 10 //1. 获取元素 11 var username = document.getElementById('username') 12 //2. 添加处理事件 13 var changeValue = function (value) { 14 console.log(this.value) 15 } 16 //3. 处理器自动选择 17 var EventUtil = { 18 addHandler: function (element, type, handler) { 19 if (element.addEventListener) { 20 element.addEventListener(type,handler,false) 21 }else if(element.attachEvent) { 22 element.attachEvent('on'+type,handler) 23 }else { 24 element['on'+type] = handler 25 } 26 }, 27 removeHandler: function (element,type,handler) { 28 if (element.removeEventListener) { 29 element.removeEventListener(type,handler,false) 30 } else if (element.detachEvent) { 31 element.detachEvent('on' + type,handler) 32 } else { 33 element['on'+type] = null; 34 } 35 } 36 } 37 //调用 38 EventUtil.addHandler(username,'change',changeValue) 39 </script> 40 </body> 41 </html>
先判断是否能使用DOM2级冒泡事件处理,如果不能则判断IE事件处理器,仍然不行则使用DOM0级