Javascript addEventListener 和 attachEvent 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30914727/
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
What is the difference between addEventListener and attachEvent?
提问by RaJesh RiJo
This is the code i used in my page,
这是我在页面中使用的代码,
if (window.addEventListener) {
window.addEventListener("load", createIframe, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", createIframe);
}
else {
window.onload = createIframe;
}
Please explain me that where my createIframefuntion get called? and what is the difference between addEventListenerand attachEvent? and what is the different between loadand onload? totally confused to find difference between addEventLisener with load and attachEvent with onload
请解释我的createIframe函数在哪里被调用?addEventListener和attachEvent之间有什么区别?load和onload 有什么区别?完全困惑地发现addEventLisener with load 和 attachEvent with onload之间的区别
回答by Hyman
Quick answer: you have to use attachEvent
if your browser returns undefined == window.addEventListener
. Thing is the former is a non-standard JS function implemented in IE8 and previous versions, while addEventListener
is supported by IE9+ (and all the other browsers).
快速回答:attachEvent
如果您的浏览器返回undefined == window.addEventListener
. 事情是前者是在 IE8 及以前版本中实现的非标准 JS 功能,而addEventListener
IE9+(以及所有其他浏览器)支持。
So the big question is: are you gonna support IE8-?
所以最大的问题是:你会支持 IE8- 吗?
Margin note: window.onload = whatever
will override any attached event listeners. This is why addEventListener
is used: to add a function to the event's stack, instead of overwriting it.
边注:window.onload = whatever
将覆盖任何附加的事件侦听器。这就是为什么addEventListener
使用:将函数添加到事件堆栈中,而不是覆盖它。