Simple instance of onclick event in DIV dynamically added by js

  • 2021-07-04 18:11:20
  • OfStack

The simplest thing is this:


<input type="button" onclick="alert(this.value)" value=" I am  button" />

Add onclick events dynamically:


<input type="button" value=" I am  button" id="bu">
<script type="text/javascript">
var bObj=document.getElementById("bu");
bObj.onclick= objclick;
function objclick(){alert(this.value)};
</script>

If you use the anonymous function function () {}, it looks like this:


<input type="button" value=" I am  button" id="bu">
<script type="text/javascript">
var bObj=document.getElementById("bu");
bObj.onclick=function(){alert(this.value)};
</script>

In fact, the above methods have 1 principle, which defines the value of onclick attribute. It is worth noting that if obj. onclick is defined multiple times, for example: obj. onclick=method1; obj. onclick=method2; obj. onclick=method3, then only the last definition obj. onclick=method3 will take effect, and the first two definitions have been overwritten by the last one.

Look at attachEvent in IE again:


<input type="button" value=" I'm bin Laden " id="bu">
<script type="text/javascript">
var bObj = document.getElementById("bu");
bObj.attachEvent("onclick",method1);
bObj.attachEvent("onclick",method2);
bObj.attachEvent("onclick",method3);
function method1(){alert(" No. 1 1 A alert")}
function method2(){alert(" No. 1 2 A alert")}
function method3(){alert(" No. 1 3 A alert")}
</script>

The execution order is method3 > method2 > method1, first in, then out, is similar to a variable in the stack. Note that the first parameter in attachEvent begins with on, which can be onclick/onmouseover/onfocus and so on

It is said (without verification) that it is best to use detachEvent after using attachEvent in IE to free up memory

Look at addEventListener in Firefox again:


<input type="button" value=" I'm Bush " id="bu">
<script type="text/javascript">
var bObj = document.getElementById("bu");
bObj.addEventListener("click",method1,false);
bObj.addEventListener("click",method2,false);
bObj.addEventListener("click",method3,false);
function method1(){alert(" No. 1 1 A alert")}
function method2(){alert(" No. 1 2 A alert")}
function method3(){alert(" No. 1 3 A alert")}
</script>

As you can see, the order of execution in ff is method1 > method2 > method3, just opposite of IE, first in, first out. It should be noted that addEventListener has three parameters, and the first one is the event name without "on", such as click/mouseover/focus.


Related articles: