问题描述
如何克服被覆盖的事件处理程序?
我有一个脚本说a.js
How to overcome event handlers being overridden?I have a script say a.js
window.onload = function () {
//Handler in a.js
}
另一个脚本说b.js
Another script say b.js
window.onload = function () {
//Handler in b.js
}
其中,
a.js是一种第三方图书馆建成由我
a.js is a kind of 3rd party library built by me
b.js是使用我的脚本的发布者[我不能在这里做任何更改]
b.js is a publisher who uses my script [I can't do any changes out here]
b.js中的onload处理程序是否会覆盖a.js的处理程序?
Will onload handler in b.js override a.js's handler?
如果是,如何防止这种情况发生?
If yes, How to prevent this from happening?
是否会在a.js中构建所有事件处理程序的队列并在事件帮助中将它们解除?
Will building a queue of all event handlers in a.js and deque them on event help?
但是a.js会知道所有事件处理程序是否已经加载了一个事件,直到加载b.js?
But will a.js know all event handlers for an event upfront untill b.js is loaded?
思考和参考将有所帮助
推荐答案
在下层使用 element.addEventListener
或 window.attachEvent
IE版本。
Use element.addEventListener
or window.attachEvent
in down-level IE versions.
示例 addEvent
方法:
Sample addEvent
method:
function addEvent(node, type, listener) {
if (node.addEventListener) {
node.addEventListener(type, listener, false);
return true;
} else if (node.attachEvent) {
node['e' + type + listener] = listener;
node[type + listener] = function() {
node['e' + type + listener](window.event);
}
node.attachEvent('on' + type, node[type + listener]);
return true;
}
return false;
};
注意 - 大多数(如果不是全部)现代JavaScript库,如 jQuery
和 MooTools
都有自己的实现。我建议利用他们的API - 因为他们抽象出不同的浏览器实现并经过全面测试。
Note - Most, if not all, modern JavaScript libraries like jQuery
and MooTools
have their own implementations. I recommend leveraging their API's - as they abstract out different browser implementations and have been thoroughly tested.
这篇关于防止window.onload被覆盖javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!