javascript attachEvent 在 IE > 8.0 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20180046/
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
attachEvent Doesn't work in IE > 8.0
提问by user3029098
I'm using attachEvent for a while, but it seems that IE doesn't support this anymore?
我使用 attachEvent 有一段时间了,但 IE 似乎不再支持它了?
window.attachEvent("onload",Start_Wysiwyg);
window.attachEvent("onscroll",ScrollEditBar,false);
Does anyone have a solution for this problem?
有没有人有解决这个问题的方法?
回答by ajp15243
.attachEvent()
is deprecated in IE9+, and has been removed in IE11.
.attachEvent()
在 IE9+ 中已弃用,并已在 IE11 中删除。
The standard is .addEventListener()
(MSDN docs). The MDN docs have a section about compatibility.
标准是.addEventListener()
(MSDN 文档)。MDN 文档有一个关于兼容性的部分。
You can simply run some feature-checking code to check if the supported features exist:
您可以简单地运行一些功能检查代码来检查支持的功能是否存在:
if (window.addEventListener) {
// Check for addEventListener first, since IE9/10 have both,
// but you should use the standard over the deprecated IE-specific one
window.addEventListener('click', myFunc);
} else if (window.attachEvent) {
window.attachEvent('onclick', myFunc);
}
If you have to attach a lot of event listeners, then you may want to just cache the desired listener attachment method in a variable and use that variable for attaching your events throughout your code, rather than having that above check for every single event listener:
如果您必须附加很多事件侦听器,那么您可能只想将所需的侦听器附件方法缓存在一个变量中,并使用该变量在整个代码中附加您的事件,而不是对每个事件侦听器进行上述检查:
var addListener = function(){}; // Default to no-op function
if (window.addEventListener) {
addListener = window.addEventListener;
} else if (window.attachEvent) {
addListener = function(eventType, listener, useCapture) {
// attachEvent wants 'oneventType' instead of 'eventType'
window.attachEvent('on'+eventType, listener, useCapture);
};
}
// Now you can add listeners with a browser-agnostic function call!
addListener('click', myFunc);
addListener('hover', myOtherFunc);
You can read more in a duplicate questionlinked by @MartyIX in a comment on your question. There are further nuances and methods in the answers/comments there, such as IE9 requiring <!DOCTYPE html>
in order to use .addEventListener()
.
您可以在@MartyIX 链接的重复问题中阅读更多关于您的问题的评论。那里的答案/评论中有进一步的细微差别和方法,例如 IE9 要求<!DOCTYPE html>
才能使用.addEventListener()
.