Example analysis of attachEvent usage in javascript

  • 2020-06-12 08:30:19
  • OfStack

This article gives an example of attachEvent usage in javascript. Share to everybody for everybody reference. The specific analysis is as follows:

1 Normally we add events to JS, like this

obj.onclick=method

This way of binding events is compatible with the major browsers, but what if you add the same event multiple times to an element?


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

If you write it this way, then only the last bound event, method3, will be executed, at which point you won't be able to write it like onclick, instead of the protagonist, we can use the attachEvent method in IE


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

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

method3- > method2- > method1

Unfortunately, this private Microsoft method is not supported by Firefox or any other browser. Fortunately, they all support the addEventListener method of the W3C standard


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">
// The first 1 Kind of way ( Microsoft's private approach )
function iniEvent() {
  var btn = document.getElementById("btn");
  btn.attachEvent("onclick", click1);
  btn.attachEvent("onclick", click2);
  btn.attachEvent("onclick", click3);
}
// The first 2 Kind of way ( Firefox and other browsers )
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>

Hopefully, this article has been helpful in your javascript programming.


Related articles: