Sometimes you need methods to load javascript events dynamically We often need to dynamically add events in JS, which is where browser compatibility comes in.
**Method 1. SetAttribute **Var obj = document. GetElementById (” obj ”); Obj. setAttribute(“onclick”, “javascript:alert(’ test ’);” );
I’m going to use setAttribute to specify the onclick attribute, simple, easy to understand,
Obj. AttachEvent (” onclick ”, Foo); The function Foo () { Alert (” test ”); }
Obj. AddEventListener (” click ”, Foo, false); The function Foo () { Alert (” test ”); }
You can also write it together Obj. addEventListener(“click”, function(){alert(” test ”); }, false);
Integrated application of
if (window.attachEvent)
{
//IE event code
}
else
{
//Event code for other browsers
}
Method 3: event = function
The addEventListener method is used for the Mozilla family
For example:
Document. The getElementById (” BTN ”). The onclick = method1; Document. The getElementById (” BTN ”). The onclick = an; Document. The getElementById (” BTN ”). The onclick = method3;
If so, only medhot3 will be executed
Write it like this: Var btn1Obj = document. GetElementById (” btn1 ”);
/ / object. AttachEvent (event, function); Btn1Obj. AttachEvent (” onclick ”, method1); Btn1Obj. AttachEvent (” onclick ”, an); Btn1Obj. AttachEvent (” onclick ”, method3); Execution order: method3-> An - > method1
Var btn1Obj = document. GetElementById (” btn1 ”); / / element. AddEventListener (type, the listener, useCapture); Btn1Obj. AddEventListener (” click ”, method1, false); Btn1Obj. AddEventListener (” click ”, an, false); Btn1Obj. AddEventListener (” click ”, method3, false);
Execution order: method1-> An - > method3
Usage examples:
**1. **
var el = EDITFORM_DOCUMENT.body;
//Get the object first, EDITFORM_DOCUMENT is actually an iframe
if (el.addEventListener){
el.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
**2. **
if (window.addEventListener) {
window.addEventListener('load', _uCO, false);
} else if (window.attachEvent) {
window.attachEvent('onload', _uCO);
}