JavaScript code writing in three different locations

Source: Internet
Author: User

There are actually many methods for writing client-side script JavaScript, and there are a lot of places to place them ..
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.