Home > Web Front-end > JS Tutorial > body text

window.addEventListener to solve the problem of letting a js event execute multiple functions_javascript skills

WBOY
Release: 2016-05-16 17:45:18
Original
1293 people have browsed it

Maybe you have also encountered this situation, that is, after using window.onload in the js code, it may affect the onload event in the body. You can write it all in the body, or you can put it all in window.onload, but this is not very convenient. Sometimes we need to use both at the same time. At this time, you need to use window.attachEvent and window.addEventListener to solve it.

Here is a solution. As for the usage of attachEvent and addEventListener, you can Google or Baidu yourself.

Copy code The code is as follows:

if (document.all){
window. attachEvent('onload', function name)//
}
else{
window.addEventListener('load', function name, false);//firefox
}

In recent work, the attachEvent method has been used. This method can attach other processing events to a certain event. Sometimes it may be useful. Here is a summary of its basic usage.

For its syntax, you can view the "DHTML Manual", which has detailed instructions. Here is an example, which comes from the Internet:
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 :
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 order is method3->method2->method1

If it is the Mozilla series, this method is not supported and you need to use addEventListener
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 order is method1->method2->method3
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!