You may have encountered this situation, that is, the onload event in the body may be affected after window. onload is used in js Code. You can write all the data in the body or in window. onload, but this is not very convenient. Sometimes we need to use both of them at the same time. In this case, we need to use window. attachEvent and window. addEventListener to solve the problem.
The following is a solution. For the usage of attachEvent and addEventListener, Google or Baidu.
Copy codeThe Code is as follows:
If (document. all ){
Window. attachEvent ('onload', function name) // in IE
}
Else {
Window. addEventListener ('load', function name, false); // firefox
}
In recent work, the attachEvent method is used. This method can append other processing events to an event, which may be useful sometimes. Here we will summarize its basic usage.
For more information about its syntax, see the DHTML manual. Here is an example from the Internet:
Copy codeThe Code is as follows:
Document. getElementById ("btn"). onclick = method1;
Document. getElementById ("btn"). onclick = method2;
Document. getElementById ("btn"). onclick = method3;
If this is the case, only medhot3 will be executed.
Write it like this:
Copy codeThe Code is as follows:
Var btn1Obj = document. getElementById ("btn1 ");
// Object. attachEvent (event, function );
Btn1Obj. attachEvent ("onclick", method1 );
Btn1Obj. attachEvent ("onclick", method2 );
Btn1Obj. attachEvent ("onclick", method3 );
The execution sequence is method3-> method2-> method1
If the Mozilla series does not support this method, you need to use addEventListener.
Copy codeThe Code is as follows:
Var btn1Obj = document. getElementById ("btn1 ");
// Element. addEventListener (type, listener, useCapture );
Btn1Obj. addEventListener ("click", method1, false );
Btn1Obj. addEventListener ("click", method2, false );
Btn1Obj. addEventListener ("click", method3, false );
The execution sequence is method1-> method2-> method3