Basic JavaScript knowledge

Source: Internet
Author: User
Tags comment tag html comment
ArticleDirectory
    • Javascript Introduction
    • How to Implement Javascript
    • Where to place Javascript
    • Javascript statements
    • Javascript Variables
    • Javascript Operators
    • Javascript branch statement
    • Javascript message box
    • JavaScript Functions
    • Javascript loop
    • JavaScript For... in Declaration
    • Javascript events
    • Javascript try... catch statement
    • Javascript throw Declaration
    • Special JavaScript characters
    • Javascript guidelines

Javascript is a Web scripting language!

Javascript is used by millions of web pages to improve design, validate forms, detect browsers, create cookies, and more applications.

Javascript is the most popular scripting language on the Internet.

Javascript is easy to use! You will love it!

 

Javascript Introduction

In millions of pages, JavaScript is used to improve design, validate forms, detect browsers, create cookies, and so on. Javascript is the most popular scripting language on the Internet and can run in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and opera.

What is JavaScript?
  • Javascript is designed to add interactions to HTML pages.
  • Javascript is a scripting language (the scripting language is a lightweightProgramming Language).
  • Javascript is executed by several lines of computersCode.
  • Javascript is usually directly embedded into HTML pages.
  • Javascript is an interpreted language (that is, code execution is not precompiled ).
  • All users do not need to buy a license to use JavaScript.

What can JavaScript do?

Javascript provides HTML designers with a programming tool.
HTML creators are often not ProgramBut Javascript is a scripting language with extremely simple syntax! Almost everyone has the ability to put short code snippets into their HTML pages.
Javascript can add dynamic text to HTML pages.
A JavaScript declaration similar to this can put a variable piece of text on an HTML page: Document. Write ("
Javascript can respond to events
You can set JavaScript to be executed only when an event occurs. For example, when a page is loaded or an HTML element is clicked.
Javascript can read and write HTML elements.
Javascript can read and change the content of HTML elements.
Javascript can be used to verify data
Javascript can be used to verify the data before it is submitted to the server.
Javascript can be used to detect visitors' browsers
Javascript can be used to detect the visitor's browser and load the corresponding page for the browser based on the detected browser.
Javascript can be used to create cookies.
Javascript can be used to store and retrieve information on the visitor's computer.

The actual name is ecmascript.

The official name of JavaScript is "ecmascript ". This standard is developed and maintained by ECMA. ECMA-262 is the formal JavaScript standard. This standard is based on JavaScript (Netscape) and JScript (Microsoft ). The Brendan eich of Netscape (navigator 2.0) invented the language and has appeared in all Netscape and Microsoft browsers since 1996. The development of ECMA-262 began in 1996, and in July 1997, The ECMA Member Conference adopted its first version. In 1998, the standard became an international ISO standard (ISO/IEC 16262 ). This standard is still under development.

 

How to Implement Javascript

The HTML <SCRIPT> label is used to insert JavaScript code into the HTML page.

Method 1:

<Script language = "JavaScript" type = "text/JavaScript">
Document. Write ("this is the text output by JavaScript ");
</SCRIPT>

Method 2:

<SCRIPT src = "One. js"> </SCRIPT>

How to deal with old browsers

Browsers that do not support JavaScript will display scripts as page content. To prevent this, we can use the following HTML comment Tag:

<SCRIPT type = "text/JavaScript">

<! --

Document. Write ("Hello world! ");

//->

</SCRIPT>

The two front slashes at the end of the comment line are the annotation symbols of JavaScript, which will prevent the Javascript compiler from compiling this line.

 

Where to place Javascript

When a page is loaded, Javascript in the body is executed.When called, the JavaScript code in the head part is executed.

You can place any number of scripts in the document, so you can place the script both to the body and to the head part.

Note that:

In an HTML document, the script code at all locations, including the introduced external JS Code, will all become a whole. You can think of them as a class. Therefore, unexpected errors may occur due to duplicate methods or duplicate variables from different files.

 

Javascript statements

Javascript is a sequence of statements executed by the browser. These commands are used to tell the browser what to do. A semicolon is usually added at the end of each line of statements. Most people think this is a good programming habit, and this is often seen in Javascript cases on the web.

The semicolon is optional (based on JavaScript standards). The browser uses the end of the line as the end of the statement. For this reason, we often see examples with no semicolons at the end. You can use semicolons to write multiple statements in a row.

 

Javascript Variables

Rules for JavaScript variable names:

    • Variable names that are meaningful, descriptive, and meaningful
    • Variables are case sensitive (Y and Y are two different variables) [Javascript is case sensitive]
    • The variable must start with a letter or underscore
    • Variable names cannot use system keywords or reserved words

Javascript variable type:

Javascript is a weak language. Therefore, the type of a variable is determined by the data on the right of the value assignment.

 

Javascript Operators

Arithmetic Operator: +-*/% ++ --, where the "+" is also used to concatenate strings. In addition, any type + is a string.

Assignment operator: = + =-= * =/= % =

Comparison OPERATOR: ====! ==<>=<=

Logical OPERATOR: & |!

Conditional OPERATOR :? :

 

Javascript branch statement

Traditional if .. Else, if .. Else if .. Else Nesting is feasible.

In switch (N), N can be an expression, but it is usually a variable. Use break to separate it in the case structure.

 

Javascript message box

You can create three message boxes in javascript: Warning box, confirmation box, and prompt box.

The warning box is often used to ensure that users can obtain certain information. When a warning box appears, you must click OK to continue the operation.

 
Alert ("text ")

 

The confirmation box enables users to verify or accept certain information. After the confirmation box appears, you must click OK or cancel to continue the operation. If you click OK, the return value is true. If you click Cancel, the returned value is false.

 
Confirm ("text ")

 

The prompt box is often used to prompt users to enter a value before entering the page. When the prompt box appears, you need to enter a value and click "OK" or "cancel" to continue the operation. If you click OK, the returned value is the input value. If you click Cancel, the return value is null.

 
Prompt ("text", "default ")

 

JavaScript Functions

Compile the script as a function to avoid executing the script when loading the page. A function contains code that can only be executed when an event is activated or called. You can call the script anywhere on the page (if the function is embedded with an external. js file, you can even call it from other pages ).

We recommend that you define the function at the beginning of the page, that is, the

Syntax for creating a function:

Function Name () {code ...}

Function Name (var1, var2,..., varx) {code ...}

Survival of JavaScript Variables

After you declare a variable in the function, you can only access the variable in the function. After exiting the function, the variable is revoked. This type of variable is called a local variable. You can use local variables with the same name in different functions, because only the declared functions can recognize each of these variables.

If you declare a variable outside the function, all functions on the page can access the variable. The lifetime of these variables starts after they are declared and ends when the page is closed.

 

Javascript loop

When writing code, you often want to execute the same piece of code repeatedly. We can use loops to complete this function, so that we do not need to repeatedly write several lines of the same Code.

Javascript has two (and only two) Different Types of loops:
For
Number of times a piece of code is cyclically executed
While
When the specified condition is true, the code is executed cyclically.

 

 

The syntax format is the same as that of Java or. NET.

What statements can be used to directly jump out of multiple loops?

The continue statement can end the current cycle with certain conditions, and directly carry out the next cycle.

The break statement can end the loop directly if it meets certain conditions. The Code jumps to the latest statement next to the back of the loop and continues to run downward.

In. net, the GOTO statement can directly locate the specified mark as continuing to execute the code, but there is no GOTO statement in Javascript. How can we directly jump out of multiple loops?

See the following example:

 
Outerloop:// Name the outer ring statement

 
For(VaRI = 0; I <10; I ++)

 
{

 
Innerloop:// Name the inner ring statement

 
For(VaRJ = 0; j <10; j ++)

 
{

 
// Jump out of the inner ring

 
If(J> 3 ){Break;}

 
// Jump out of the inner ring

 
If(I = 2 ){BreakInnerloop ;}

 
// Jump out of the outer ring Loop

 
If(I = 4 ){BreakOuterloop ;}

 
Document. Write ("I ="+ I +", J ="+ J +"<Br/>");

}

 
}

 
Document. Write ("Final"+"I ="+ I +", J ="+ J );

You can set a flag outside the loop, and then use break or continue to add a tag name to directly jump out of the loop. Note that, unlike other languages, once a JS program jumps out, the program will not continue to execute code from the tag location again, but will directly execute the code after the outermost loop, if no code is followed, the program ends.

 

JavaScript For... in Declaration

For... in declaration is used to traverse the attributes of an array or object (loop operation on attributes of an array or object ). [Also a member of the For Loop family]

The following example uses for .. In to traverse an array object. Note the difference between foreach and. net.

 
VaRX

 
VaRMycars =NewArray ();

Mycars [0] ="Saab";

 
Mycars [1] ="Volvo";

 
Mycars [2] ="BMW";

 
 

 
For(XInMycars)

 
{

 
Document. Write (mycars [x] +"<Br/>");

 
}

 

Javascript events

Events are behaviors that can be detected by JavaScript.

Javascript enables us to create dynamic pages. Events are behaviors that can be detected by JavaScript.

Each element in the web page can generate events that can trigger JavaScript Functions. For example, when a user clicks a button, an onclick event is generated to trigger a function. Events are defined on the HTML page.

Event example:
    • Click
    • Page or image loading
    • Hover your mouse over a hotspot on the page
    • Select input box in the form
    • Confirmation Form
    • Keyboard buttons

Note: events are usually used with functions. when an event occurs, the function is executed.

 

Onload and onUnload

When a user enters or leaves the page, the onload and onUnload events are triggered. The onload event is often used to detect the browser type and version of a visitor, and then load the webpage of a specific version based on the information. Onload and onUnload events are often used to process cookies created when users enter or exit the page. For example, when a user first enters the page, you can use a message box to ask the user's name. The name is saved in the cookie. When the user enters this page again, you can use another message box to greet the user: "Welcome John Doe! ".

Onfocus, onblur and onchange

Onfocus, onblur, and onchange events are usually used together to verify the form.

The following is an example of using the onchange event. Once the user changes the domain content, the checkemail () function will be called.

<Input type = "text" size = "30" id = "email"Onchange = "checkemail ()">
Onsubmit

Onsubmit is used to verify all form fields before submitting a form.

The following is an example of using the onsubmit event. When you click the OK button in the form, the checkform () function is called. If the field value is invalid, this submission will be canceled. The Return Value of the checkform () function is true or false. If the return value is true, the form is submitted, and vice versa.

 
<Form method = "Post" Action = "xxx.htm"Onsubmit = "Return checkform ()">

 

Onmouseover and onmouseout

Onmouseover and onmouseout are used to create "dynamic" buttons.

The following is an example of using the onmouseover event. When the onmouseover event is detected by the script, a warning box is displayed:

 
<A href = "http://www.w3school.com.cn"Onmouseover = "alert ('an onmouseover event'); Return false">  </a>

 

Javascript try... catch statement JavaScript-catch Error

When surfing the internet, we will always see a javascript warning box with a runtime error, and will ask us if we want to debug it ?". Such error messages may be useful to developers, but not to users. When an error occurs, they often choose to leave the site.

There are two ways to capture errors on a webpage:

    • Use the try... catch statement. (Available in ie5 +, Mozilla 1.0, and Netscape 6)
    • Use the onerror event. This is an old-fashioned method used to capture errors. (Available in Versions later than Netscape 3)

Note: chrome, opera, and Safari do not support onerror events.. [This method is not recommended]

In the next example, a confirmation box is displayed, asking the user to choose to click the OK button when an error occurs to continue browsing the webpage, or click the cancel button to return to the homepage.

 
<HTML>

 
<Head>

 
<SCRIPT type ="Text/JavaScript">

 
VaRTXT =""

FunctionMessage ()

 
{

 
Try

 
{

 
Adddlert ("Welcome guest! ");

 
}

 
Catch(ERR)

 
{

 
TXT ="There was an error on this page. \ n";

 
TXT + ="Click OK to continue viewing this page, \ n";

 
TXT + ="Or cancel to return to the home page. \ n";

 
If(! Confirm (txt ))

 
{

 
Document. Location. href ="Http://www.w3school.com.cn /";

 
}

 
}

 
}

 
</SCRIPT>

 
</Head>

 
<Body>

<Input type ="Button"Value ="View message"Onclick ="Message ()"/>

 
</Body>

 
</Html>

 

Javascript throw Declaration

The role declared by throw is to create an exception ). You can use this declaration with the try... catch declaration to control program streams and generate precise error messages.

The following example is used to determine the value of variable X. If the value of X is greater than 10 or less than 0, the error is throw ). After this error is captured by the catch parameter, the custom error message is displayed.

 
<HTML>

 
<Body>

 
<SCRIPT type ="Text/JavaScript">

VaRX = prompt ("Enter a number between 0 and 10 :","");

 
Try

 
{

 
If(X> 10)

 
Throw "Err1";

 
Else If(X <0)

 
Throw "Err2";

 
}

 
Catch(ER)

 
{

 
If(ER ="Err1")

 
Alert ("Error! The value is too high");

 
If(ER ="Err2")

 
Alert ("Error! The value is too low");

 
}

 
</SCRIPT>

 
</Body>

</Html>

 

Special JavaScript characters

You can use a backslash in JavaScript to add special characters to a text string.

A backslash is used to insert ellipsis, line breaks, quotation marks, and other special characters into a text string.

See the following JavaScript code:

 
VaR TXT = "We Are the so-called"Vikings"From the north. "document. Write (txt)

In JavaScript, strings start or end with single or double quotation marks. This means that the above string will be truncated to: We are the so-called.

To solve this problem, you must add a backslash (\) before the quotation marks in "VIKING (\). In this way, each double quotation mark can be converted to a literal string.

 
VaR TXT = "We Are the so-called\ "Vikings \"From the north. "document. Write (txt)

Now javascript can output the correct text string: We are the so-called "Vikings" from the north.

 

Javascript guidelines Javascript is case sensitive

A function named "myfunction" and a function named "myfunction" are two different functions. Similarly, variables "myvar" and variables "myvar" are different. Javascript is case sensitive-so when you create or use variables, objects, and functions, pay attention to the Case sensitivity of characters.

 

Space

Javascript ignores unnecessary spaces. Therefore, you can add appropriate spaces in the code to make the code more readable. The following two rows are equivalent:

 
Name = "hege" name = "hege"

 

Line feed

You can use a backslash to lines the code within a text string. The following example is correct:

 
Document. Write ("Hello \ world! ")

But it cannot be broken like this:

 
Document. Write \ ("Hello world! ")

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.