Design and Application of JavaScript client scripts

Source: Internet
Author: User
Tags script tag

Basic JavaScript concepts

Javascript is an object-based and event-driven scripting language with secure performance. It was originally created by Netscape and named live script, it has only one relationship with Java: The name is similar. It is used with HTML hypertext markup language, Java scripting language (Java smallProgram) Link multiple objects in a web page to interact with Web customers. This allows you to develop client applications. It is implemented through embedding or calling in a standard HTML language. Its appearance makes up for the defects of the HTML language. It is a compromise between Java and HTML. (Note: Like VBScript, JavaScript has a server version)

I. Basic JavaScript syntax

0. Introduction

The syntax of JavaScript is basically the same as that of Java. However, because Javascript is a weak scripting language, it may be different in programming. At the same time, because Javascript is an object-based language, it is not an object-oriented language, so it has some defects in object support, such as object inheritance that everyone is familiar, polymorphism and other basic features of object-oriented languages can only be implemented in Javascript through some flexible means (usually complicated ). However, the weak type language also has its advantages, that is, simplicity. The type conversion in Javascript is very convenient (the weak type language in Code Basically, it is non-typed). A string can be converted to an int (equivalent to calling integer. parseint (string) through a simple addition/subtraction operation, without throwing an exception. Javascript, as an explanatory language, can also use eval statements that are difficult to support in compiling languages C/C ++ and Java. Javascript runs in a sandbox with many security restrictions. It cannot access local hard disks, store data on servers, modify or delete network documents, and can only browse or dynamically interact with information through a browser, this effectively prevents data loss. In general, JavaScript should have both advantages and disadvantages (dialectical representation =]).
As a Java graduate student, it is not difficult to learn JavaScript. Javascript is not an empirical field like HTML and CSS. Once you get started, the JavaScript-related learning in the remaining stages is likely to be reading materials. Here I hope that the content I have written can serve as a reference and lay the foundation for everyone. The following content is mainly about JavaScript. I will describe it from the keywords and emphasize the keywords to give you a comprehensive understanding of JavaScript syntax, some keywords may not be used in future development, but I think it is necessary for you to understand them and pay attention to the notes marked here. Then there will be four ways to add scripts to the page. In "javascript client programming", I will refer to the browser documentation (DOM) model and event model, where how to find objects and install the event processor (event processing ing). Finally, I will give a piece of core code annotation and three examples in the "javascript sample. The "javascript learning materials" contains some useful book names, electronic reference materials and related websites. Please pay attention to the recommended reference materials and mlparser user guide. I will answer your JavaScript question in the FAQ.
For the first time, errors are inevitable. Please correct and understand.

1. var

VaR I = 5;
VaR J = "Hello World ";
VaR K = document;
For (VAR u = 0 ;...;...){...}
Function fun () {var v = Document ;...}
The function of VaR is to declare variables, but variables that are not declared through VaR can also be used.
Variables declared with VAR in block blocks (code segments enclosed by {And} Or (and) are local variables. Once the block scope is exceeded ), the variable will become invalid. For example, in the u and v variables in the example, when the program stream has a range of for and function statements, U and V become undefined variables.
In other cases, variables declared with VAR or directly used without declaration (the interpreter implicitly declares these variables) are global variables.

In the same scope, the same variable name cannot use more than once var, that is, the variable cannot be declared repeatedly.
Variables with the same name declared in different scopes are hidden in Javascript. For example, there is a global variable and a local variable in the program segment, the variable you reference in the program will actually be a local variable.

After a variable is assigned a value, its type is converted to the assigned type.
The variable value that has never been declared (including the implicit declaration caused by the value assignment operation) is of the undefined type and undefined type.

The validity of a variable is that its definition range is irrelevant to the sequence in which the definition statement appears.
Function Test (){
Document. Write (great); // print "undefined"
Document. Write (ODD); // print "javas", not "undefined"
VaR odd = "javas ";
}
In the example, although odd is after document. Write, odd is initialized when the program is interpreted. Therefore, the printed result is not "undefined" but the initial value assigned by odd.

2. If-Else

If (Val> 2.3 ){
Rs = 5.56;
}
Else if (Val + RS> "1.2 "){
Rs = document;
}
Else {
Rs = "Hello World ";
}
The IF-else usage is exactly the same as that in Java.
Note that "Val + RS> '1. 2'" in the expression is not allowed in Java.
In addition, although JavaScript does not require extra points after each sentence, adding a semicolon is a good programming habit.
Variables that are used without declaration in the example are allowed in JavaScript and are automatically converted to global variables.
Javascript is case sensitive, so pay attention to the Case sensitivity of keywords.

3. Switch

Switch (key-65 ){
Case 0:
Ch = "";
Break;
Case 1:
Ch = "B ";
Break;
Default:
Ch = "X ";
Break;
Case 9:
Ch = "Y ";
Break;
}
The switch usage is exactly the same as that in Java.
We recommend that you use constant expressions (integers and strings) instead of floating points for variables followed by case.
The break statement at the end of each case is usually indispensable unless you want to use the switch fall-through to implement specific functions.
The default statement can be placed anywhere in the switch structure, and can be placed across case statements.

4. While

While (I <0 & bool_var ){
If (I>-5)
Continue;
I + = 3 + I;
}
The usage of while is exactly the same as that in Java.
If it is a bool variable, you can directly use it without writing bool_var = true/false.
The contine statement skips the remaining statements in the loop and enters the next iteration of the loop.
There are also break and continue with label in Javascript, which are used in the same way as Java.
When writing a loop, be sure not to generate an "dead" loop. In the sample program segment, there is an "endless" loop.

5. Do-while

Do {
I-= 8;
} While (I> 0 );
The usage of do-while is exactly the same as that in Java.
Do not omit the semicolon after the while (expression) end.

6.

For (VAR I = 0; I <8; I ++ ){
Document. writeln ("Hello world! ");
}
The usage of do-while is exactly the same as that in Java.
Do not add the int type identifier before counting variable I. Javascript is a weak type language. If int is added, a syntax error is reported, but VaR can be used to make it a local variable.
For (...;...;...) the content between Semicolons can be blank (for (;) is equivalent to while (true), where multiple statements can be separated by commas.

7. For-in

For (VAR ite in document ){
Str_result + = Document [ite];
}
The for-in control statement does not exist in Java. Its function is similar to that described by the iterator interface in Java. In the example, ite will traverse all the elements that can be traversed (not all) in docment, ITE will contain the index string of the retrieved array or object (which can be considered as the object name), for example, textfield (if you have an element ID in the page as textfield ), or like numbers 1, 2, and 3 (they are used to reference unnamed elements in an object ).
When referencing elements in an object, use the join array method: array name or object name [index value]. In this example, document [ite] is used to represent the element indexed as ite in document.
The biggest benefit of using for-in is that you do not need to know the number of elements in the target object or array, and what the internal structure is, you can traverse all of its traversal elements.

8. Continue-break

Again:
While (test ()){
Whie (is_run ){
If (Work ()){
Break again;
// Continue again;
}
Reap ();
}
I ++;
}
The usage of continue-break is exactly the same as that in Java.
You can use a break or continue with a label to jump in an internal or external loop.

9. Function

Function fun_1 (arg1, arg2 ){
Rs = arg1 + arg2;
Return Rs;
}
Function writing in Javascript differs greatly from that in Java.
First, there is a problem with the parameter type. There is no need to add any type description before the parameter, and VAR cannot be added. JavaScript method parameters can also be divided into passing values and passing references. The rules are basically the same as those in Java. For details, refer to relevant materials.
The second is the return value. The type of the return value does not need to be specified. Return returns the corresponding object. If no return data exists, the return value is undefined. In this sense, functions always return values.
Finally, there is a problem with the number of parameters. The parameter list does not limit the number of parameters actually passed in to the function. It only provides a shortcut to access parameters, that is, a specific name is given to parameters at a specific location.

Sum = fun_1 (1 );
The above function is called and only passed to fun_1. (two parameters are required when fun_1 is defined ). What is the value of arg2 at this time? Undefined, you guessed it.
We can change fun_1 to the following form to cope with this situation.
Function fun_2 (arg1, arg2 ){
If (! Arg1) arg1 = 0;
If (! Arg2) arg2 = 0;
Rs = arg1 + arg2;
Return Rs;
}
Undefined is equivalent to false in a Boolean expression.

Okay, the problem seems to have been solved. But what if we want to process more parameters? For example, the following function calls represent the situation.
Sum = fun_2 (1, 2, 3 );
There is an arguments object in the function, which is an array of parameters that can be used to access all parameters of the input function.
Based on this feature, we changed fun_2 to fun_3.
Function fun_3 (){
Rs = 0;
For (VAR I = 0; I <arguments. length; I ++ ){
RS + = parseint (arguments [I]);
}
Return Rs;
}
Note: parseint is used here instead of implicit conversion caused by direct addition. This is because implicit conversion is too demanding and may convert rs to another internal type.
0 + "23a" = Nan; 0 + parseint ("23a") = 23

Function Point (x, y) {
This. X = x;
This. y = y;
This. func = m_func;
}< br> function m_func (Num ){...}
var newpoint = new point (1, 3);
newpoint. func (newpoint. X + new point. y);
Any function can be a constructor. The this keyword in the function is similar to that in Java, but not identical.
objects generated through new are eventually cleared through the garbage collection mechanism.
A function is also one of the internal types of JavaScript, so it can be assigned to a variable. Be careful not to add (). () is actually an operator that represents the call to the function.
This. func = m_func; indicates that the m_func function is assigned to the func member variable of this.
This. func = m_func (); indicates that the return value of the m_func function call is assigned to the func member variable of this.

Object member access is similar to Java: Object Name. member name
To add a new member to a class, you only need to assign values to a specific member name (undefined is read if no value is assigned). In fact, global variables or functions are the member attributes and methods of top-level objects, from this perspective, you can easily understand the variable declaration rules described in the VaR section.

In JavaScript, since a function is regarded as a type, the declaration of a function is similar to that of a common variable:
VaR my_func = new function ("arg1", "arg2 ",..., "argn", "Var rs = arg1 + arg2 +... + argn; Return Rs ;");
VaR my_func = function (arg1, arg2,..., argn)
{
VaR rs = arg1 + arg2 +... + argn;
Return Rs;
};
The former is called the constructor method, and the latter is called the direct method.

10. Prototype

Function Point (x, y ){
This. x = X;
This. Y = y;
// This. func = m_func;
}
Point. Prototype. func = m_func;
Point. Prototype. s_name = "point ";
Function m_func (Num ){...}
New Point ();
VaR newpoint = new point (1, 3 );
Newpoint. func (newpoint. x + new point. y );
Prototype indicates the prototype. I changed the point implementation in section 9. Grant m_func to the prototype of the point.
The only benefit of this change is that we don't have to assign values to the func attribute every time we call the point function. The func attribute is saved in the prototype object of the point, thus saving the memory space. For details about the relationship between point and point. prototype, refer to relevant materials.
Prototype can be used to implement static variables and static methods in Java (Some browsers create prototype objects only after an object is created, therefore, we recommend that you call the constructor method once before using static members in the prototype object, for example, the new point (); statement in the same example. After the call is completed, useless objects will be recycled, however, the prototype object will continue to reside in the memory). The limited inheritance of objects supported by JavaScript is also related to prototype.

11. Array

VaR arr_8 = new array (8 );
VaR arr = new array ();
VaR arr_d = [1, 2, 4,..., "Hi", null, true, document];
VaR arr_m = [1, 2, 3, 4], [5, 6, 7], [8];

Arr_8 [3] = "ABC ";
Arr [100] = 8.8888;
Arr_d [0] = "CDE ";
Arr_m [1] [0] = "XYZ ";
To create an array, you can use the new array constructor method (the parameter is the initial length of the array, and the null parameter indicates the zero length ).
Or [data, data ,..., the array of data] is directly assigned to the variable. Data is separated by commas. Two consecutive commas (,) in the blue part of arr_d indicate that the third element is vacant and its value is undefined.
Examples of constructor Methods: arr_8 and ARR; examples of direct Arrays: arr_d and arr_m.

The array in Javascript is a dynamic array, which automatically adjusts the array length as the number of elements increases.
The array elements in Javascript do not have any type restrictions. The uninitialized element value is undefined.
The implementation of multidimensional arrays in Javascript is exactly the same as that in Java. In arr_m, [1, 2, 3, 4] indicates the data in the second-dimensional array pointed to by arr_m [0.
The access to arrays by JavaScript is exactly the same as that in Java.

VaR textfield = Document. All ["textfield"];
Is document. All an array? Not all.
So why can we use "textfield" to access our objects?
This is because what we see above is a very special usage in Javascript-associating arrays, which can also be called the indexer.
Object Name ["member name"] = Object Name. member name

The use of correlated Arrays can free some operations from hard encoding to make them more flexible. See the following example.
If we need to rely on external output to execute an object-related operation, we can determine the called function.
Solution: Switch. This method needs to be updated every time a branch is changed.
Solution 2: Object +. + function name ();, syntax error.
Solution 3: object [function name string] ();, OK.
Solution 4: eval (Object Name string + "." + function name string + "();");, or.

The use of correlated arrays enables us to use strings, numbers, or other types of variables as indexes to access the attributes and methods we need to access.
This method is often used in for-each to traverse object or array attributes and methods.

12. UNDEFINDED-NULL

Undefined = NULL? True
Undefined === null? False
Undefined indicates that the referenced object is not defined.
Null indicates that the value of the referenced object is null.
In a Boolean expression, its function is basically the same as that in null, and both represent false.

13. Try-catch-finally-Throw

Try {
Throw new error ("test exception ");
}
Catch (e ){
Document. writeln (E. Name + ":" + E. Message );
}
Finally {
Document. writeln ("final here ");
}
Try-catch-finally-throw is used exactly the same as that in Java.
This is a new feature of JavaScript 1.5, which may not be supported in early browsers. Currently, Internet Explorer 6, nav7, opera, and Firefox 1.0 are commonly used.

14.

Function Point (x, y ){
This. x = X;
This. Y = y;
}
VaR newpoint = new point (1, 3 );
With (newpoint ){
VaR sum = x + y;
}
The use of with is exactly the same as that in delph.
Because with is used, newpoint. X and newpoint. y are simplified to X and Y respectively.

15. typeof

Swich (typeof OBJ ){
Case "string ":
Rs = "string ";
Break;
Case "object ":
Rs = "object ";
Break;
Case "Number ":
Rs = "Number ";
Break;
Defualt:
Rs = "unknown type ";
}
Typeof is used to return the string corresponding to the Data Type in the variable.
The string returned by typeof varies with the browser.

2. Use JavaScript on the webpage

1. In the URL marked by the link

<A href = "javascript: Alert ('Hi! '); "> Click me </a>
Click me
This method is usually used only in teaching demonstration.
The "javascript: //" protocol header in href must be added. Multiple scripts can be written, but return statements cannot be written.

2. In the event processing attribute of HTML tags

<A href = "#" onclick = "javascript: Alert ('Hello! '); Return false; "> click me too </a>
Click me too
This method is simple and common. Return false is used to prevent page jumps.
Generally, the "javascript: //" protocol header can be left blank, abbreviated as onclick = "alert ('Hello! '); Return false ;".

3. In the script tag of the page

<Script language = "JavaScript" type = "text/JavaScript">
<! -- // --> <! [CDATA [//> <! --
Function testjs (){
Alert ('Hello! ');
...
}
// --> <!]>
</SCRIPT>
...
<A href = "#" onclick = "testjs (); Return false;"> click me again </a>
Click me again
In this way, scripts and HTML are separated, and the overall structure of the Code is relatively good.
Add <! -- // --> <! [CDATA [//> <! -- And // --> <!]> It is to avoid scripts being output as common text in browsers that do not support scripts.
Similarly, the <NoScript> label displays prompt text when the browser does not support scripts.
<SCRIPT> labels are usually placed in

4. In the external script file

[testjs. js]
function testjsext () {
alert ('ohhh no! ');
...
}< br> // -->
[*. htm]

...
click me nowww!
click me nowww!
An external script stores the script in a separate *. js file and introduces the script by specifying the src attribute of the

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.