Home >Web Front-end >JS Tutorial >Simple example of onclick event in DIV dynamically added by js
: The easiest thing is: 单
<input type="button" onclick="alert(this.value)" value="我是 button" />
dynamic adding onClick event:
<input type="button" value="我是 button" id="bu"> <script type="text/javascript"> var bObj=document.getElementById("bu"); bObj.onclick= objclick; function objclick(){alert(this.value)}; </script>
If you use anonymous function function () {}, as shown below:
R<input type="button" value="我是 button" id="bu"> <script type="text/javascript"> var bObj=document.getElementById("bu"); bObj.onclick=function(){alert(this.value)}; </script>E
above above In fact, the principles of the methods are the same, they all define the value of the 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 of obj.onclick=method3 will take effect, and the first two definitions will take effect. The definitions of have been overwritten by the last one.
Look at attachEvent in IE:
<input type="button" value="我是拉登" 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("第一个alert")} function method2(){alert("第二个alert")} function method3(){alert("第三个alert")} </script>
The execution order is method3 > method2 > method1 , first in, last out, similar to variables in the stack. It should be noted that the first parameter in attachEvent starts with on, which can be onclick/onmouseover/onfocus, etc.
It is said (without confirmation) that after using attachEvent in IE, it is best to use detachEvent to release memory
again Take a look at addEventListener in Firefox:
<input type="button" value="我是布什" 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("第一个alert")} function method2(){alert("第二个alert")} function method3(){alert("第三个alert")} </script>