JavaScript Basics
JavaScript is a scripting language that belongs to the web!
JavaScript is used by millions of of pages to improve design, verify forms, detect browsers, create cookies, and more.
JavaScript is the most popular scripting language on the Internet.
JavaScript is easy to use! You're going to love it!
Introduction to JavaScript
On 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 works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera.
What is JavaScript?
JavaScript is designed to add interactive behavior to HTML pages.
JavaScript is a scripting language (the scripting language is a lightweight programming language).
JavaScript consists of several lines of executable computer code.
JavaScript is usually embedded directly into an HTML page.
JavaScript is an explanatory language (that is, code execution is not precompiled).
All people can use JavaScript without having to purchase a license.
What can JavaScript do?
JavaScript provides a programming tool for HTML designers HTML creators are often not programmers, but JavaScript is a scripting language with a very simple syntax! Almost everyone has the ability to put short snippets of code into their HTML pages.JavaScript can put dynamic text in an HTML page a piece of JavaScript that resembles this can put a variable piece of text in an HTML page: document.write ("JavaScript can respond to events JavaScript can be set to be executed when an event occurs, such as when a page is loaded or when a user taps an HTML element.JavaScript can read and write HTML elements JavaScript can read and change the contents of HTML elements.JavaScript can be used to validate data JavaScript can be used to validate data before it is committed 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 that resides on a visitor's computer.
The real name is ECMAScript.
The official name of JavaScript is "ECMAScript". This standard is developed and maintained by the ECMA organization. ECMA-262 is the official JavaScript standard. This standard is based on JavaScript (Netscape) and JScript (Microsoft). Brendan Eich of Netscape (Navigator 2.0) invented the language, which has been in all Netscape and Microsoft browsers since 1996. The development of ECMA-262 began in 1996, and in July 1997, the ECMA Membership Conference adopted its first version. In 1998, the standard became the International ISO Standard (IEC 16262). This standard is still in development.
How to implement JavaScript
HTML <script> tags are used to insert JavaScript code into HTML pages.
Way One:
<script language= "javascript" type= "Text/javascript" >
document.write ("This is the text output by JavaScript");
</script>
Way two:
<script src= "One.js" ></script>
How to deal with an old browser
Browsers that do not support JavaScript will display the script as the content of the page. To prevent this from happening, we can use such HTML comment tags:
<script type="text/javascript">
<!--
document.write("Hello World!");
//—>
</script>
The two forward slash at the end of the comment line is a JavaScript comment symbol that prevents the JavaScript compiler from compiling the line.
Where to place JavaScript
when the page is loaded, JavaScript is executed in the body section. when called, JavaScript in the head section is executed.
You can place any number of scripts in the document, so you can either place the script in the body or place it in the head section.
It is important to note that:
In an HTML document, all the location of the script code, including the introduction of the external JS code, they will become a whole. You can think of them as being in a class. Therefore, sometimes duplicate methods or duplicate names from different files can cause unexpected errors to occur.
JavaScript statements
JavaScript is a sequence of statements executed by the browser. The purpose of these commands is to tell the browser what to do. You typically add a semicolon 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 (according to the JavaScript Standard), and the browser ends the line as the end of the statement. For this reason, you will often see examples with no semicolons at the end. By using semicolons, you can write multiple statements in a single line.
JavaScript variables
Rules for JavaScript variable names:
There should be some meaningful, descriptive, words too literally variable names.
Variables are case sensitive (Y and Y are two different variables) "JavaScript is case sensitive"
The variable must start with a letter or an underscore
Variable name cannot use System keyword or reserved word
Types of JavaScript variables:
JavaScript is a weakly typed language, so the type of the variable is determined by the data to the right of the assignment number.
JavaScript operators
Arithmetic operator: +–*/% + +--where the + sign is also overloaded for stitching strings, and any type + on string is a string.
Assignment operator: = = = = *=/=%=
Comparison operators: = = = = = = = = = > < >= <=
Logical operator:&& | | !
Conditional operator:? :
JavaScript Branch Statements
The traditional If. Else,if. else if: The nesting of else is possible.
N in switch (n) can be an expression, but it is usually a variable, and the case structure also needs to be separated by break.
JavaScript message box
You can create three message boxes in JavaScript: A warning box, a confirmation box, and a prompt box.
Warning boxes are often used to ensure that users can get some information. When the warning box appears, the user needs to click the OK button to continue the operation.
Alert ("Text")
The confirmation box is used to enable users to verify or accept certain information. When the confirmation box appears, the user needs to click the OK or Cancel button to continue the operation. If the user clicks Confirm, then the return value is true. If the user clicks Cancel, the return value is false.
Confirm ("text")
The prompt box is often used to prompt the user to enter a value before entering the page. When the prompt box appears, the user needs to enter a value and then click the Confirm or Cancel button to continue the manipulation. If the user clicks Confirm, then the return value is the value entered. If the user clicks Cancel, the return value is null.
Prompt ("text", "Default value")
JavaScript functions
By writing a script as a function, you can avoid executing the script when the page is loaded. Functions contain code that can only be activated by an event, or executed when a function is called. You can invoke the script anywhere in the page (if the function embeds an external. js file, it can even be called from another page).
It is recommended to define the function at the start of the page, that is, the
syntax for creating a function:
Function name () {code ... }
Function name (var1,var2,..., varx) {code ... }
The lifetime of a JavaScript variable
When you declare a variable within a function, you can only access the variable in that function. When you exit the function, the variable is revoked. This variable is called a local variable. You can use local variables with the same name in different functions, because only the function that declares the variable can recognize each of these variables.
If you declare a variable outside of a function, all functions on the page can access the variable. The lifetimes of these variables begin after they are declared and end when the page closes.
JavaScript Loops
When writing code, you often want to execute the same piece of code over and over again. We can use loops to do this, so we don't have to write several lines of the same code repeatedly.
There are two types of JavaScript (there are only 2) of different kinds of loops:ForLoop a piece of code to execute a specified number of timesWhileLoop execution code when the specified condition is true
Syntax format and Java or. NET is the same.
What statements can be used to jump out of multiple loops directly?
The continue statement can end the cycle in accordance with certain conditions, and proceed directly to the next round cycle.
The break statement can end the loop directly under certain conditions, and the code jumps to the last statement that goes out of the loop to continue execution down.
In. NET, a goto statement can be positioned directly to the specified tag to continue executing code, and in JavaScript there is no goto statement, so how do you jump out of multiple loops directly?
Look at the following example:
Named Outer RING statement
for (var i=0; i<10; i++)
{
Innerloop://name Inner ring statement
for (var j=0; j<10; J + +)
{
Jump out of the inner ring loop
if (j>3) {break;}
Jump out of the inner ring loop
if (i==2) {breakinnerloop;}
Jump out of outer ring loop
if (i==4) {breakouterloop;}
document.write ("i =" +i+ ", j =" +j+"<br/>");
}
}
document.write ("final" +"i =" +i+ ", j =" +j ");
You can set the tag to outside the loop and then jump out of the loop using break or continue plus the tag name. Note here that, unlike other languages, when you jump out of JS, the program will not continue to execute the code from the tag bit, but directly after the outermost loop, if there is no code, then the program ends.
JavaScript for ... In declaration
For ... In declarations are used to iterate over an array or an object's properties (to iterate over a group or an object's properties). [also a member of the For Loop family]
The following example uses the for: In iterating over an array object, note the difference between foreach in. NET.
var x
New Array ();
"Saab";
"Volvo";
"BMW";
In Mycars)
{
"<br/>");
}
JavaScript Events
Events are behaviors that can be detected by JavaScript.
JavaScript gives us the ability to create dynamic pages. Events are behaviors that can be detected by JavaScript.
Each element in a Web page can produce certain events that can trigger JavaScript functions. For example, we can trigger a function by generating an OnClick event when the user taps a button. The event is defined in the HTML page.
Examples of events:
Mouse click
Page or image loading
Hovering over a hotspot on a page
Select an input box in the form
Confirmation form
Keyboard keys
Note: Events are usually used in conjunction with a function, which is performed when an event occurs.
OnLoad and OnUnload
The onload and OnUnload events are triggered when the user enters or leaves the page. The onload event is commonly used to detect the browser type and version of a visitor and then load a specific version of the page based on that information. OnLoad and OnUnload events are also often used to process cookies that are created when a user enters or leaves the page. For example, when a user enters a page for the first time, you can use a message box to ask for the user's name. The name will be stored 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 often work with each other to validate the form.
Here is an example of using the OnChange event. Once the user changes the contents of the domain, the Checkemail () function is called.
onchange="checkEmail()">
OnSubmit
OnSubmit is used to validate all form fields before submitting a form.
Here is an example of using the OnSubmit event. The Checkform () function is called when the user clicks on the confirmation button in the form. If the value of the field is not valid, the 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, conversely, the commit is canceled.
onsubmit="return checkForm()">
OnMouseOver and onmouseout
OnMouseOver and onmouseout are used to create "dynamic" buttons.
Here is an example of using the OnMouseOver event. When the OnMouseOver event is detected by the script, a warning box pops up:
onmouseover="alert(‘An onMouseOver event‘);return false"></a>
JavaScript Try ... Catch statement JavaScript-catch error
When we surf the web, we always see Javascript warning boxes with runtime errors, and ask us "Do you want to debug?" ”。 Error messages like this may be useful to developers, not to users. When errors occur, they often choose to leave the site.
There are two ways to catch errors in a Web page:
Use the Try...catch statement. (Available in ie5+, Mozilla 1.0, and Netscape 6)
Use the OnError event. This is an old-fashioned way to catch errors. (Netscape 3 later available)
Note: Chrome, opera, and Safari browsers do not support OnError events . "This method is not recommended"
The next example displays a confirmation box that allows the user to choose whether to continue browsing the page by clicking the OK button when an error occurs, or by clicking the Cancel button to return to the homepage.
<script type="Text/javascript" >
var txt=""
Function message ()
{
Try
{
Adddlert ("Welcome guest!");
}
catch (Err)
{
"There was a error on this page.\n\n";
"Click OK to continue viewing this page,\n";
"or Cancel to return to the home page.\n\n";
if (!confirm (TXT))
{
document.location.href="http://www.w3school.com.cn/";
}
}
}
</script>
<body>
<input type="button" value="View message" onclick="message ()"/>
</body>
JavaScript Throw Declaration
The purpose of the throw declaration is to create a exception (exception). You can use this statement in conjunction with the Try...catch declaration to achieve the purpose of controlling the flow of the program and generating accurate error messages.
The function of the following example is to determine the value of the variable x. If the value of X is greater than 10 or less than 0, the error is thrown (throw). When the error is captured by the catch parameter, a custom error message is displayed.
<body>
"Text/javascript" >
var x = prompt ("Enter a number between 0 and ten:", "");
Try
"ERR1";
if (x<0)
"ERR2";
catch (er)
{
Alert ("error! The value is too ");
Alert ("error! The value is too low ");
}
</script>
</body>
JavaScript Special Characters
You can use backslashes in JavaScript to add special characters to a text string.
Backslashes are used to insert ellipses, line breaks, quotation marks, and other special characters in a text string.
Take a look at the following JavaScript code:
"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 as: We are the so-called.
To solve this problem, you must precede the quotation marks in the "Viking" with the backslash (\). This allows you to convert each double quotation mark to a literal string.
\"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
The function named "MyFunction" and the function named "MyFunction" are two different functions, and the variable "MyVar" and the variable "MyVar" are also different. JavaScript is case sensitive-so when you create or use variables, objects, and functions, be aware of the case of the characters.
Space
JavaScript ignores extra spaces. So you can add the appropriate spaces in your code to make your code more readable. The following two lines are equivalent:
Name= "Hege" name = "Hege"
Line break
You can use backslashes inside a text string to wrap the code. The following example is correct:
document.write ("Hello world!")
But you can't fold a line like this:
document.write ("Hello world!")
Basic knowledge of JavaScript