The easiest thing is this:
<input type="button" onclick="alert(this.value)" value="I am a button" />
Dynamically add onclick event:
<input type="button" value="I am a 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 is as follows:
<input type="button" value="I am a button" id="bu"><script type="text/javascript">var bObj=document.getElementById("bu");bObj.onclick=function(){alert(this.value)};</script>The above methods are actually the same principle, they all define the value of the onclick attribute. It is worth noting that if obj.onclick is defined multiple times, such as: obj.onclick=method1; obj.onclick=method2; obj.onclick=method3, then only the last definition obj.onclick=method3 will take effect, and the previous two definitions are overwritten by the last one.
Let’s look at the attachEvent in IE again:
<input type="button" value="I am 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("first alert")}function method2(){alert("second alert")}function method3(){alert("third alert")}</script>The execution order is method3 > method2 > method1 , first in and then out, similar to the variables in the stack. It should be noted that the first parameter in attachEvent starts on, which can be onclick/onmouseover/onfocus, etc.
It is said that (unconfirmed verification) it is best to use detachEvent to free memory after using attachEvent in IE.
Let's take a look at the addEventListener in Firefox:
<input type="button" value="I am 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("first alert")}function method2(){alert("second alert")}function method3(){alert("third alert")}</script>As you can see, the execution order in ff is method1 > method2 > method3, which is exactly the opposite of IE, first in first out. It should be noted that addEventListener has three parameters. The first is the event name without "on", such as click/mouseover/focus, etc.
The simple example of the onclick event in the DIV dynamically added by js is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.