Javascript addEventListener() / attachEvent() 的正确用法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2657182/
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
Correct usage of addEventListener() / attachEvent()?
提问by ginny
I'm wondering how to use addEventListenerrespectively attachEventcorrectly?
我想知道如何addEventListener分别attachEvent正确使用?
window.onload = function (myFunc1) { /* do something */ }
function myFunc2() { /* do something */ }
if (window.addEventListener) {
window.addEventListener('load', myFunc2, false);
} else if (window.attachEvent) {
window.attachEvent('onload', myFunc2);
}
// ...
or
或者
function myFunc1() { /* do something */ }
if (window.addEventListener) {
window.addEventListener('load', myFunc1, false);
} else if (window.attachEvent) {
window.attachEvent('onload', myFunc1);
}
function myFunc2() { /* do something */ }
if (window.addEventListener) {
window.addEventListener('load', myFunc2, false);
} else if (window.attachEvent) {
window.attachEvent('onload', myFunc2);
}
// ...
?
?
Is this cross-browser secure or should I better go with something like this:
这是跨浏览器安全还是我应该更好地使用这样的东西:
function myFunc1(){ /* do something */ }
function myFunc2(){ /* do something */ }
// ...
function addOnloadEvent(fnc){
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", fnc, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", fnc );
}
else {
if ( window.onload != null ) {
var oldOnload = window.onload;
window.onload = function ( e ) {
oldOnload( e );
window[fnc]();
};
}
else
window.onload = fnc;
}
}
addOnloadEvent(myFunc1);
addOnloadEvent(myFunc2);
// ...
AND: Say myfunc2is for IE 7 only. How to modify the correct/preferred method accordingly?
并且:说myfunc2仅适用于 IE 7。如何相应地修改正确/首选方法?
回答by hitautodestruct
The usage of both is similar, though both take on a slightly different syntax for the event parameter:
两者的用法相似,但两者的 event 参数语法略有不同:
addEventListener (mdn reference):
addEventListener(mdn 参考):
obj.addEventListener('click', callback, false);
function callback(){ /* do stuff */ }
Events listfor addEventListener.
事件列表的addEventListener。
attachEvent (msdn reference):
attachEvent(msdn 参考):
obj.attachEvent('onclick', callback);
function callback(){ /* do stuff */ }
Events listfor attachEvent.
事件列表的attachEvent。
Arguments
参数
For both of the methods the arguments are as follows:
1. Is the event type.
2. Is the function to call once the event has been triggered.
3. (addEventListeneronly)If true, indicates that the user wishes to initiate capture.
对于这两种方法,参数如下:
1. 是事件类型。
2. 事件触发后调用的函数。
3. (addEventListener仅)如果为真,表示用户希望启动捕获。
Explanation
解释
Both methods are used to achieve the same goal of attaching an event to an element.
The difference being is that attachEventcan only be used on older tridentrendering engines ( IE5+IE5-8*) and addEventListeneris a W3 standard that is implemented in the majority of other browsers (FF, Webkit, Opera, IE9+).
这两种方法都用于实现将事件附加到元素的相同目标。
不同之处在于attachEvent它只能用于较旧的三叉戟渲染引擎(IE5+IE5-8*),并且addEventListener是在大多数其他浏览器(FF、Webkit、Opera、IE9+)中实现的 W3 标准。
For solid cross browser event support including normalizations that you won't get with the Diaz solution use a framework.
对于可靠的跨浏览器事件支持,包括使用 Diaz 解决方案无法获得的规范化,请使用框架。
*IE9-10 support both methods, for backwards compatibility.
*IE9-10 支持这两种方法,以实现向后兼容。
Thanks to Luke Puplettfor pointing out that attachEventhas been removed from IE11.
感谢Luke Puplett指出它attachEvent已从 IE11 中删除。
Minimal cross browser implementation
最小的跨浏览器实现
As Smittyrecommended you should take a look at this Dustin Diaz addEventfor a solid cross browser implementation without the use of a framework:
正如Smitty建议的那样,您应该看看这个Dustin Diaz addEvent以获得可靠的跨浏览器实现,而无需使用框架:
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
}
else if (obj.attachEvent) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() {obj["e"+type+fn](window.event);}
obj.attachEvent("on"+type, obj[type+fn]);
}
else {
obj["on"+type] = obj["e"+type+fn];
}
}
addEvent( document, 'click', function (e) {
console.log( 'document click' )
})
回答by Smitty
Anyone still hitting this discussion and not finding the answer they were looking for checkout:
http://dustindiaz.com/rock-solid-addevent
任何人仍然参与这个讨论并且没有找到他们正在寻找的答案结帐:http:
//dustindiaz.com/rock-solid-addevent
This is one of the most elegant solutions I found for those of us with restrictions on using the frameworks.
这是我为我们这些限制使用框架的人找到的最优雅的解决方案之一。
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
EventCache.add(obj, type, fn);
} else if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function() {
obj["e" + type + fn](window.event);
}
obj.attachEvent("on" + type, obj[type + fn]);
EventCache.add(obj, type, fn);
} else {
obj["on" + type] = obj["e" + type + fn];
}
}
var EventCache = function() {
var listEvents = [];
return {
listEvents: listEvents,
add: function(node, sEventName, fHandler) {
listEvents.push(arguments);
},
flush: function() {
var i, item;
for (i = listEvents.length - 1; i >= 0; i = i - 1) {
item = listEvents[i];
if (item[0].removeEventListener) {
item[0].removeEventListener(item[1], item[2], item[3]);
};
if (item[1].substring(0, 2) != "on") {
item[1] = "on" + item[1];
};
if (item[0].detachEvent) {
item[0].detachEvent(item[1], item[2]);
};
item[0][item[1]] = null;
};
}
};
}();
addEvent(window, 'unload', EventCache.flush);

