I recently used JavaScript event processing mechanism and found some information.
When writing JavaScript programs in the past, events were all used
Object.event = handler;
is initialized. This method is common for Internet Explorer, Mozilla/Firefox and Opera. But one problem is that this method can only correspond to one event processing process. It is not easy to use if you want an event to execute multiple processing processes in sequence.
But Internet Explorer has provided an attachEvent method since 5.0. Using this method, you can assign multiple processing processes to an event. attachEvent is also applicable to current Opera. But the problem is that Mozilla/Firefox does not support this method. But it supports another addEventListener method, which is similar to attachEvent and is also used to assign multiple processing procedures to an event. But there are some differences in the events they assign. In the attachEvent method, the event starts with "on", but in addEventListener, the event does not start with "on". In addition, addEventListener has a third parameter. Generally, this parameter is specified as false. That's it.
So if you want to assign multiple processing procedures to an event in your program, you only need to first determine the browser, and then choose to use attachEvent or addEventListener according to different browsers. The example is as follows:
if (document.all) {
window.attachEvent('onload', handler1);
window.attachEvent('onload', handler2);
}
else {
window.addEventListener('load', handler1, false) ;
window.addEventListener('load', handler2, false);
}
Note: The execution order of multiple processes assigned by attachEvent is random, so the execution order between these processes is random. Don't have order dependencies. In addition, attachEvent and addEventListener are not only applicable to window objects, but other objects also support this method.
function addEvent(obj, evenTypeName, fn){
if (obj.addEventListener){
obj.addEventListener(evenTypeName, fn, true);
return true;
} else if (obj.attachEvent){
return obj.attachEvent("on " evenTypeName, fn);
} else {
return false;
}
}