The simplest is:
<Input type = "button" onclick = "alert (this. value)" value = "I Am a button"/>
Dynamically add an 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 the anonymous function () {} is used, it is shown below:
<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 have the same principle. They all define the values of The onclick attribute. It is worth noting that if multiple definitions of obj. onclick, for example, obj. onclick = method1; obj. onclick = method2; obj. onclick = method3, only the last defined obj. onclick = method3 takes effect. The previous two definitions overwrite the last one.
Let's look at attachEvent in IE:
<Input type = "button" value = "I am 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 ("First alert ")}
Function method2 () {alert ("second alert ")}
Function method3 () {alert ("third alert ")}
</Script>
The execution sequence is method3> method2> method1, Which is advanced and later, similar to the variables in the stack. Note that the first parameter in attachEvent starts with "on", which can be "onclick/onmouseover/onfocus", etc.
It is said that (unconfirmed) it is best to use detachEvent to release memory after using attachEvent in IE
Let's take a look at addEventListener in Firefox:
<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 ("First alert ")}
Function method2 () {alert ("second alert ")}
Function method3 () {alert ("third alert ")}
</Script>
We can see that the execution order in ff is method1> method2> method3, which is just opposite to IE, first-in-first-out. Note that addEventListener has three parameters. The first parameter is the name of an event without "on", such as click/mouseover/focus.