Home  >  Article  >  Web Front-end  >  How to use javascript attachEvent and addEventListener_javascript skills

How to use javascript attachEvent and addEventListener_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:55:131123browse

attachEvent method button onclick
addEventListener method button click
The principle of using both: they can have different execution priorities. The following examples are explained as follows:
attachEvent method attaches other processing events to a certain event. (Mozilla series is not supported)
addEventListener method is used for Mozilla series
Example:
Java code

Copy code The code is as follows:

document.getElementById("btn").onclick = method1;
document.getElementById("btn").onclick = method2;
document.getElementById(" btn").onclick = method3;

If written like this, then only medhot3 will be executed
Written like this:
Java code:
Copy code The 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 it is the Mozilla series, this method is not supported, and you need to use addEventListener
Java code:
Copy code The 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
Usage example:
1. Java code:
Copy code The code is as follows:

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. Java code:
Copy code The code is as follows:

if (window.addEventListener){
window.addEventListener('load', _uCO, false);
} else if (window.attachEvent){
window.attachEvent('onload', _uCO);
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn