Home > Web Front-end > JS Tutorial > Methods and codes for adding events to elements under javascript_form effects

Methods and codes for adding events to elements under javascript_form effects

WBOY
Release: 2016-05-16 19:10:23
Original
1155 people have browsed it

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>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template