Home >Web Front-end >JS Tutorial >Example analysis of attachEvent usage in javascript_javascript skills

Example analysis of attachEvent usage in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:59:021174browse

The example in this article describes the usage of attachEvent in javascript. Share it with everyone for your reference. The specific analysis is as follows:

Generally we add events in JS like this

obj.onclick=method

This method of binding events is compatible with mainstream browsers, but what if the same event is added multiple times to an element?

obj.onclick=method1
obj.onclick=method2
obj.onclick=method3

If you write it like this, then only the last bound event, here method 3, will be executed. At this time, we can’t use onclick. The protagonist has changed. In IE, we can use the attachEvent method

btn1Obj.attachEvent("onclick",method1);
btn1Obj.attachEvent("onclick",method2);
btn1Obj.attachEvent("onclick",method3);

The format is preceded by the event type. Note that you need to add on, such as onclick, onsubmit, onchange. The execution order is

method3->method2->method1

Unfortunately, this Microsoft private method is not supported by Firefox and other browsers. Fortunately, they all support the W3C standard addEventListener method

btn1Obj.addEventListener("click",method1,false);
btn1Obj.addEventListener("click",method2,false);
btn1Obj.addEventListener("click",method3,false);

The execution order is method1->method2->method3

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>attachEvent</title>
<script type="text/javascript">
//第一种方式(微软的私人方法)
function iniEvent() {
  var btn = document.getElementById("btn");
  btn.attachEvent("onclick", click1);
  btn.attachEvent("onclick", click2);
  btn.attachEvent("onclick", click3);
}
//第二种方式(火狐和其他浏览器)
function iniEvent2() {
  var btn = document.getElementById("btn");
  btn.addEventListener("click", click1, false);
  btn.addEventListener("click", click2, false);
  btn.addEventListener("click", click3, false);
}
function click1() {
  alert('click1');
}
function click2() {
  alert('click2');
}
function click3() {
  alert('click3');
}
</script>
</head>
<body onload="iniEvent()">
<input type="button" id="btn" value="attachEvent" />
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

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