我对 if (obj.attachEvent) {...}
block 中的代码感到困惑。我在查看此页面时发现了这个示例:http://codebits.glennjones.net/cheatsheet/javascript.htm#events
无论如何,有人可以解释一下这段代码在做什么吗?我假设 obj
是一个 DOM 元素,type
是事件的类型(例如 click
或 hover
),fn
是回调函数。
function addEvent(obj, type, fn) {
if (obj) {
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.addEventListener(type, fn, false);
}
}
};
我总是使用以下代码来执行跨浏览器事件附件(没有 jQuery)。上述方法比我所做的更好吗?
function attachEvent(element, type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, fn);
}
};
最佳答案
在下面的代码中注释:
if (obj.attachEvent) { //if the browser supports the attachEvent method
obj['e' + type + fn] = fn; //store the handler
obj[type + fn] = function () { obj['e' + type + fn](window.event); }; //create the callback that invokes the handler stored above
obj.attachEvent('on' + type, obj[type + fn]); //Attach an event handler to the on<event>, such as onclick
} else {
obj.addEventListener(type, fn, false); //otherwise, default to browsers supporting addEventListener
}
关于javascript - 将事件添加到 DOM 元素时,此代码如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8727893/