javascript Event.observe(window, "load", function(){..} v/s window.onload = function(){..}

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12859122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:16:34  来源:igfitidea点击:

Event.observe(window, "load", function(){..} v/s window.onload = function(){..}

javascriptprototypejs

提问by Shreedhar

Even though both do the samething, i just want to know is there any specific advantage using one over another?

即使两者都做同样的事情,我只想知道使用一个比另一个有什么特定的优势吗?

Event.observe(window, "load", function(){
//do something
});

window.onload = function(){
//do something
}

回答by Andries

The difference is that window.onloadis defined in the DOM Level 0 Event Model and will erase all earlier registed events. It's an 'native' call from an old API.

不同之处在于window.onloadDOM Level 0 Event Model 中定义的,将删除所有早期注册的事件。这是来自旧 API 的“本机”调用。

The Event.observefrom the prototype javascript framework will determine the best event attacher available. A facade pattern. In modern browsers, the addEventListenerwill be called - attachEventin case of Internet Explorer below version 9. In old browsers the onloadwill be called.

Event.observe从原型javascript框架将确定附加器提供最佳的事件。立面图案。在现代浏览器中,addEventListener将被调用 -attachEvent在版本 9 以下的 Internet Explorer 的情况下。在旧浏览器中,onload将被调用。

It obvious that a facade will choose the best option available, like Event.observefor prototype or .loadin case of jQuery for example.

很明显,外观将选择可用的最佳选项,例如Event.observe原型或.loadjQuery。

The methods from the DOM Level 2 Event Model are preferred over the DOM Level 0 Event Model methods because they act as observers and don't erase previous handlers.

DOM 级别 2 事件模型中的方法优于 DOM 级别 0 事件模型方法,因为它们充当观察者并且不会删除以前的处理程序。

回答by Bergi

Read quirksmode.org's introduction into events. The difference is between the traditional modeland the advanced models, which need a wrapper because M$ does/did not support the W3-standard and a distinction needs to be made.

阅读 quirksmode.org 对事件介绍。区别在于传统模型高级模型之间需要一个包装器,因为 M$ 不支持/不支持 W3 标准并且需要进行区分。