Javascript事件监听

来源:互联网 发布:52单片机论坛 编辑:程序博客网 时间:2024/05/16 11:49
firefox中addEventListener()方法和ie中attachEvent()方法都是为HTML元素添加一个事件监听

为什么要采用事件监听而不是直接对元素的事件属性(如:onclick、onmouseover)赋值?

这两种方法处理事件还是有很大区别的!事件属性只能赋值一种方法,即:
  1. button1.onclick = function() { alert(1); };
  2. button1.onclick = function() { alert(2); };
这样后面的赋值语句就将前面的onclick属性覆盖了。
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Coda Bubble Example</title>
  5. </head>
  6. <body>
  7. <button id="Button1">测试</button>
  8. <script type="text/javascript">
  9. /// <summary>
  10. /// 添加事件监听
  11. /// </summary>
  12. /// <param name="target">载体</param>
  13. /// <param name="type">事件类型</param>
  14. /// <param name="func">事件函数</param>
  15. function addEventHandler(target, type, func) {
  16.     if (target.addEventListener)
  17.         target.addEventListener(type, func, false);
  18.     else if (target.attachEvent)
  19.         target.attachEvent("on" + type, func);
  20.     else target["on" + type] = func;
  21. }
  22. /// <summary>
  23. /// 移除事件监听
  24. /// </summary>
  25. /// <param name="target">载体</param>
  26. /// <param name="type">事件类型</param>
  27. /// <param name="func">事件函数</param>
  28. function removeEventHandler(target, type, func) {
  29.     if (target.removeEventListener)
  30.         target.removeEventListener(type, func, false);
  31.     else if (target.detachEvent)
  32.         target.detachEvent("on" + type, func);
  33.     else delete target["on" + type];
  34. }
  35. var Button1 = document.getElementById("Button1");
  36. var Button1Click = function() { alert(1); };
  37. addEventHandler(Button1, "click",  Button1Click);
  38. addEventHandler(Button1, "click", function() { alert(2); } );
  39. addEventHandler(Button1, "click", function() { alert(3); } );
  40. removeEventHandler(Button1, "click", function() { alert(2); } ); // 移不出
  41. removeEventHandler(Button1, "click", Button1Click); // 可以移除
  42. </script>
  43. </body>
  44. </html>
而添加事件监听就可以并行。

特别是当团队合作时,事件并行的需求增多,比如:监听document对象的鼠标事件或者window对象的载入事件等。
使用事件属性则很容易造成事件覆盖掉。

经过测试IE(8)中先显示3再显示2,而firefox(3)中则先显示2再显示3
这个是为什么呢?测试的结果即真理,没啥好想的。囧