Home >Web Front-end >JS Tutorial >Methods and codes for adding events to elements under javascript_form effects
The simplest is this:
Dynamicly add onclick event:
If using anonymous function function(){} , as shown below:
The above methods actually have the same principle, 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 The definitions of have been overwritten by the last one.
Look at the attachEvent in IE:
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 it Memory
Look at addEventListener in Firefox:
<script> <BR>var bObj=document.getElementById("bu"); <BR>bObj.onclick= objclick; <BR>function objclick(){alert(this.value)}; <BR></script> <script> <BR>var bObj=document.getElementById("bu"); <BR>bObj.onclick=function(){alert(this.value)}; <BR></script>You can see that the execution order in ff is method1 > method2 > method3 , just the opposite of IE, first in, first out. It should be noted that addEventListener has three parameters. The first one is the event name without "on", such as click/mouseover/focus, etc. <script> <BR>var bObj = document.getElementById("bu"); <BR>bObj.attachEvent("onclick",method1); <BR>bObj.attachEvent("onclick",method2); <BR>bObj.attachEvent("onclick",method3); <BR>function method1(){alert("第一个alert")} <BR>function method2(){alert("第二个alert")} <BR>function method3(){alert("第三个alert")} <BR></script><script> <BR>var bObj = document.getElementById("bu"); <BR>bObj.addEventListener("click",method1,false); <BR>bObj.addEventListener("click",method2,false); <BR>bObj.addEventListener("click",method3,false); <BR>function method1(){alert("第一个alert")} <BR>function method2(){alert("第二个alert")} <BR>function method3(){alert("第三个alert")} <BR></script>