Javascript事件监听

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
这个是为什么呢?测试的结果即真理,没啥好想的。囧

<script type="text/javascript"> function viewPage() { var view = document.getElementById("TextareaView"); var win = window.open('', '', ''); win.opener = null; win.document.write(view.value); win.document.close(); }</script>
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值