Recently I used the JavaScript event processing mechanism and found some information.
When I used to write JavaScript programs, all events used
Copy codeThe Code is as follows: object. event = handler;
. This method is common for Internet Explorer, Mozilla/Firefox, and Opera. However, one problem is that this method only corresponds to one event processing process. If you want an event to be able to execute multiple processing procedures in sequence, it is not easy to use.
However, Internet Explorer provides an attachEvent method from 5.0. With this method, you can assign multiple processing processes to an event. AttachEvent is also applicable to Opera. But the problem is that Mozilla/Firefox does not support this method. However, it supports another addEventListener method, which is similar to attachEvent and is used to assign multiple processing processes to an event. However, there are some differences between the events they assign. In the attachEvent method, the events start with "on", and in the addEventListener, the "on" with no start with the event ", in addition, addEventListener has a third parameter. Generally, this parameter can be set to false.
Therefore, to assign multiple processing processes to an event in your program, you only need to first determine the browser, and then choose whether to use attachEvent or addEventListener based on different browsers. Example:Copy codeThe Code 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 sequence of multiple processes assigned by attachEvent is random, so there should be no sequential dependency between these processes. In addition, attachEvent and addEventListener are not only applicable to window objects, but also some other objects support this method.Copy codeThe Code is as follows: 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;
}
}