The following describes how to write JavaScript code in three different places. To achieve this, click the button to bring up the alert warning box.
The first is the most common. The Code is as follows:
Html code
<Input type = "button" value = "button 1" id = "btn1" onclick = "pop ()">
Js Code
Function pop ()
{
Alert ("calling in JavaScript Functions ");
}
The second method is the simplest implementation method. The Code is as follows:
<Input type = "button" value = "button 2" id = "btn2" onclick = "javascript: alert ('write function directly ');">
The third method is relatively complex. The Code is as follows:
Html code
<Input type = "button" value = "button 3" id = "btn3">
Js Code
Var obj = document. getElementById ("btn3"); // The following statements must be placed under the definition of btn3; otherwise, the compiler cannot recognize btn3.
If (window. addEventListener) // Mozilla, Netscape, Firefox, and other browsers
{
Obj. addEventListener ("click", fun, false); // pay attention to false.
}
Else // IE browser
{
Obj. attachEvent ("onclick", fun );
}
Function fun ()
{
Alert ("trigger an event in a function ");
}
Summary: The effects of the three writing methods are exactly the same. It should be said that the three methods are common and have their own advantages and disadvantages ....