javascript注册window的onload事件问题研究

在真实的编程环境中,对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
 
  • A string of one event type (without the "on" prefix) known to the browser's object model. The W3C DOM knows the following event types (and Netscape 6 implements most of them):
  • A reference to the function to execute when the node hears the event type in the specified propagation mode. As this is a reference to a function object, do not surround the name in quotes, nor include the parentheses of the function. At execution time, the browser automatically passes the current event object as a parameter to the listener function.
  • A Boolean value. If true, the node listens for the event type only while the event propagates toward the target node (in event capture node). If false, the node listens only when the event bubbles outward from the event target. If the current node is the target of the event, either Boolean value may be used.

 

 

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~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值