在真实的编程环境中,对window.onload事件注册多个函数是很常见的事,但window.onload 不能同时加载多个函数。
如
则只有b函数生效。
解决方法可以是
但是代码不好看,而且还有动态参数的问题不易解决
下面先来看一下ms的解决方法 IE5以上的方法
注意只对IE5以上有效 方法说明参见 MSDN
如果想对其它浏览器使用如FF opera等则参考如下方法
addEventListener原文说明如下:
addEventListener( | NN 6 IE n/a DOM 2 |
addEventListener("eventType", listenerFunction, useCapture) | |
Binds an event handler function to the current node so that the function executes when an event of a particular type arrives at the node either as event target or during event propagation. Note that W3C DOM events propagate through text nodes, as well as element nodes. The node listens for the event type either during event capture or event bubbling propagation, depending upon the setting of the Boolean third parameter. You may invoke this method multiple times for the same node but with different parameter values to assign as many event handling behaviors as you like, but only one listener function may be invoked for the same event and propagation type. If the event listener is added on a temporary basis, it may be removed via the removeEventListener( ) method. | |
Parameters | |
|
ms给提供了一个好的方法可以兼容两种方法,很难得的是这种方法竟然是不用微软的命名,呵呵,真稀罕
看看微软是怎么让步的吧
How to Translate attachEvent to addEventListener |
The W3C DOM Level 2 Event Model specifies addEventListener as the standard way to register event handlers. For cross-browser compatibility, the following script defines addEventListener to the window object.
在页面引导时注意让语句先运行,然后就可以用方便的方法来使用了 注意上面的useCapture一般用false值即可
应用代码例
现在注册的事件都可以执行了~
~the end~