事件处理程序(addEventListener 和 attachEvent)
1.addEventListener 和 removeEventListener
接收三个参数:要处理的事件名、作为事件处理程序的函数和布尔值
缺点:不兼容IE
<body> <input type="button" value="按钮3" id="btn3"> </body> <script type="text/javascript"> function showMes(event){ alert(event.type); } var btn3 = document.getElementById('btn3'); btn3.addEventListener('click',showMes,false); btn3.addEventListener('click',function(){ alert(this.value); },false); btn3.removeEventListener('click',showMes,false); </script>
2.attachEvent和detachEvent
接收两个参数:事件处理程序的名称和事件处理程序的函数
btn3.attachEvent('onclick',showMes);
然而,我们不能光为了chrome等浏览器只用addEventListener,或者光为了IE只用attachEvent,故而要将其融合起来用
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <input type="button" value="按钮3" id="btn3"> </body> <script type="text/javascript"> function showMes(event){ alert(event.type); } var btn3 = document.getElementById('btn3'); 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.removeEventListener){ element.removeEventListener(type,handler,false); } else if(element.detachEvent){ element.detachEvent('on'+type,handler); } else{ element['on'+type] = null; } } } eventUtil.addHandler(btn3,'click',showMes); </script> </html>