JavaScript on the front

Source: Internet
Author: User
Tags define function define local function definition null null script tag variable scope

JavaScript is a footstep language that runs on the browser side, and JavaScript primarily solves the problem of front-end interaction with the user, including interacting with the data using interactions. JavaScript is performed by the browser interpreter, the front-end scripting language is also JScript (Microsoft, ie exclusive), ActionScript (Adobe, requires plugins), and so on.

Front three chunks:
1. HTML: Page structure
2, CSS: Page performance: element size, color, position, hidden or display, part of the animation effect
3, JavaScript: page behavior: Some animation effects, page and user interaction, page function

How JavaScript embeds a page

1. Inter-row events (mainly for events)

<input type= "button" Name= "onclick=" alert (' ok! ‘);" >

2. Page Script Tag embedding

<script type= "Text/javascript" >            alert (' ok! ');</script>

3. External Introduction

<script type= "Text/javascript" src= "Js/index.js" ></script>

  

variables, data types, and basic syntax specifications

JavaScript is a weakly typed language, and the variable type of JavaScript is determined by its value. Defining variables requires the keyword ' var '.

var iNum = 123; var sTr = ' ASD '; At the same time define multiple variables can be separated with ",", the common one ' var ' keyword var iNum = 45,str= ' qwe ', scount= ' 68 ';
Variable type

5 Basic data types:
1. Number Type
2. String type
3. Boolean Boolean type True or False
4, undefined undefined type, the variable declaration is not initialized, its value is undefined
5, NULL null type, represents an empty object, if the defined variable is prepared to save the object in the future, you can initialize the variable to null, the object is not obtained on the page, the value returned is null

1 Types of composite:
Object

JavaScript statements and comments

1, JavaScript statements can be indented or not indented, indentation is for the convenience of code reading, a JavaScript statement should be ";" End

<script type= "Text/javascript" >    var iNum = 123;var sTr = ' abc123 '; function Fnalert () {    alert (sTr);}; Fnalert ();</script>

2. JavaScript annotations

<script type= "Text/javascript" >    //single-line comment var iNum = 123;/*      Multiline comment    1 、...    2 、... */var sTr = ' abc123 ';</script>
variable, function, attribute, function parameter naming specification

1. Case-sensitive
2. The first character must be a letter, an underscore (_), or a dollar sign ($)
3. Other characters can be letters, underscores, dollar symbols, or numbers

Hungarian naming style:

Objects O object such as: Odiv
Arrays a array such as: Aitems
Strings s String for example: sUserName
Integer I integer For example: Iitemcount
Boolean B Boolean for example: Biscomplete
Floating point F float for example: Fprice
FUNCTIONS fn function such as: Fnhandler
Regular expressions re RegExp such as: Reemailcheck

Function

A function is a piece of code that executes repeatedly.

function definition and execution
<script type= "Text/javascript" >    //functions define function    Fnalert () {        alert (' hello! ');    }    function Execution    Fnalert ();</script>
Pre-parsing of variables and functions

The JavaScript parsing process is divided into two phases, first in the compilation phase, then in the execution phase, in advance of function-defined functions in the compile phase, and the variable declaration defined by Var is advanced, assigning it to undefined.

<script type= "Text/javascript" >        fnalert ();       Eject hello!    alert (iNum);  Eject undefined    function Fnalert () {        alert (' hello! ');    }    var iNum = 123;</script>

Parameters can be passed in functions of function-passed JavaScript.

<script type= "Text/javascript" >    function Fnalert (a) {        alert (a);    }    Fnalert (12345);</script>
function ' return ' keyword

The function of the ' return ' keyword:
1. Return values or objects in a function
2. End Function operation

<script type= "Text/javascript" >function Fnadd (inum01,inum02) {    var iRs = iNum01 + iNum02;    return iRs;    Alert (' here! ');} var iCount = Fnadd (3,4); alert (iCount);  Eject 7</script>
Conditional statements

Conditional statements are required to control the direction of the program through conditions.

Conditional operators

= =, = =, >, >=, <, <=,! =, && (and), | | (OR),! No

If Else
var iNum01 = 3;var iNum02 = 5;var str;if (inum01>inum02) {    sTr = ' greater than ';} else{    sTr = ' less than ';} alert (STR);
Multiple if Else statements
var inow = 1;if (inow==1) {    ...;} else if (inow==2) {    ...;} else{...    ;}
Get Element method

You can use the getElementById method on the built-in object document to get the element that sets the id attribute on the page, get an HTML object, and assign it to a variable, such as:

<script type= "Text/javascript" >    var odiv = document.getElementById (' Div1 '); </script>....<div id= "Div1" > This is a DIV element </div>

The above statement, if the JavaScript is written on the element, it will be wrong, because the page from the top load execution, javascript to get the element div1 on the page, the element Div1 has not been loaded, there are two ways to solve:

The first method: Place JavaScript at the bottom of the page

..... <div id= "Div1" > This is a DIV element </div>....<script type= "Text/javascript" >    var odiv = document.getElementById (' Div1 ');</script></body>

The second method is to put the JavaScript statement into the function that the window.onload triggers, and the statement that gets the element is executed after the page has been loaded, so there is no error.

<script type= "Text/javascript" >    window.onload = function () {        var odiv = document.getElementById (' Div1 ') ;    } </script>....<div id= "Div1" > This is a DIV element </div>
Manipulating element properties

Gets the page element that can manipulate the properties of the page element, including the property's read and write operations.

Manipulating element properties

var variable = element. Property name Read Property
Element. Property Name = new Property Value Override property

The wording of attribute name in JS

1, the HTML attributes and JS inside the same wording
2, "class" attribute written "ClassName"
3, "style" attribute inside the property, there is a cross-bar to the hump, such as: "Font-size", changed to "Style.fontsize",

<script type= "Text/javascript" >    window.onload = function () {        var oinput = document.getElementById (' Input1 ');        var OA = document.getElementById (' Link1 ');        Read attribute value        var svalue = oinput.value;        var stype = Oinput.type;        var sName = oinput.name;        var slinks = oa.href;        Write (set) property        OA.style.color = ' red ';        OA.style.fontSize = svalue;    } </script>......<input type= "text" name= "SetSize" id= "input1" value= "20px" ><a href= "/http Www.baidu.com "id=" Link1 "> Baidu </a>
InnerHTML

innerHTML can read or write the contents of the label package

<script type= "Text/javascript" >    window.onload = function () {        var odiv = document.getElementById (' Div1 ') ;        Read        var sTxt = odiv.innerhtml;        alert (STXT);        Write        odiv.innerhtml = ' <a href= ' http://www.baidu.com ' > Baidu <a/> ';    } </script>......<div id= "Div1" > This is a DIV element </div>
Event properties and anonymous function event properties

Elements in addition to the style, ID and other properties, there are event properties, the common event properties have the mouse click event Properties (onclick), mouse move into the event properties (mouseover), the mouse out of the event properties (mouseout), the function name assigned to the element event properties, Events and functions can be associated.

<script type= "text/javascript" >window.onload = function () {    var obtn = document.getElementById (' btn1 ');    Obtn.onclick = Myalert;    function Myalert () {        alert (' ok! ');}    } </script>
anonymous functions

The defined function can not give the name, this is called anonymous function, you can assign the definition of anonymous function directly to the element's event property to complete the event and function Association, so as to reduce the function name, and simplify the code. If a function is a public function, it can be written in the form of an anonymous function.

<script type= "text/javascript" >window.onload = function () {    var obtn = document.getElementById (' btn1 ');    /*    Obtn.onclick = Myalert;    function Myalert () {        alert (' ok! ');    }    *    ///Assign anonymous function directly to the bound event    Obtn.onclick = function () {        alert (' ok! ')    }} </script>
Arrays and how to manipulate them

An array is a collection of data, and in JavaScript, the data inside the array can be of different types.

Methods for defining arrays
An instance of the object is created with var alist = new Array, or//direct amount created by var aList2 = [n/A, ' ASD '];
Methods for manipulating data in an array

1, get the length of the array: alist.length;

var alist = [1,2,3,4];alert (alist.length); Pop Up 4

2. Use subscript to manipulate an array of data: alist[0];

var alist = [1,2,3,4];alert (alist[0]); Pop up 1

3. Join () merges the array member into a string by a delimiter

var alist = [1,2,3,4];alert (Alist.join ('-')); Eject 1-2-3-4

4. Push () and pop () add or remove members from the last array

var alist = [1,2,3,4];alist.push (5); alert (alist); Pop-up 1,2,3,4,5alist.pop (); alert (alist); Eject 1,2,3,4

5. Reverse () reverses the array

var alist = [1,2,3,4];alist.reverse (); alert (alist);  Eject 4,3,2,1

6, IndexOf () returns the index value of the first occurrence of an element in an array

var alist = [1,2,3,4,1,3,4];alert (Alist.indexof (1));

7. Splice () Add or remove members from the array

var alist = [1,2,3,4];alist.splice (2,1,7,8,9); Starting with the 2nd element, delete the 1 elements and add the ' 7,8,9 ' three element alert (alist) at this position; Eject 1,2,7,8,9,4
Multidimensional arrays

A multidimensional array is a member of an array and an array of arrays.

var alist = [[1,2,3],[' A ', ' B ', ' C ']];alert (alist[0][1]); Eject 2;

To manipulate the data in an array in bulk, you need to use the Loop statement

Looping statements

Regular repetitive operations in the program require the use of loop statements.

For loop
for (Var i=0;i<len;i++) {    ...}
Example: Array de-weight
var alist = [1,2,3,4,4,3,2,1,2,3,4,5,6,5,5,3,3,4,2,1];var aList2 = [];for (var i=0;i<alist.length;i++) {    if ( Alist.indexof (Alist[i]) ==i)    {        alist2.push (alist[i]);}    } alert (ALIST2);
String processing methods

1. String merge operation: "+"

var iNum01 = 12;var iNum02 = 24;var sNum03 = ' n '; var sTr = ' abc '; alert (inum01+inum02)  ; Eject 36alert (inum01+snum03);  The popup 1212 number and string addition are equivalent to the string addition alert (SNUM03+STR);     Eject 12ABC

2. parseint () converts a numeric string to an integer

var = ' sNum01 '; var sNum02 = ' $ '; var sNum03 = ' 12.32 '; alert (snum01+snum02)  ; Eject 1224alert (parseint (SNUM01) +parseint (SNUM02))  //Eject 36alert (parseint (SNUM03))   //Eject number 12 Converts a string decimal to a numeric integer

3. parsefloat () converts a numeric string to a decimal number

var sNum03 = ' 12.32 ' Alert (parsefloat (SNUM03));  Pop-up 12.32 converts a string decimal to a decimal number

4. Split () separates a string into an array of strings

var sTr = ' 2017-4-22 '; var arr = Str.split ("-"); var arr2= str.split (""); alert (arr);  Eject [' ~ ', ' 4 ', ' 2 ']alert (ARR2);  Eject [' 2 ', ' 0 ', ' 1 ', ' 7 ', '-', ' 4 ', '-', ' 2 ', ' 2 ']

5, IndexOf () find if the string contains a character

var sTr = "Abcdefgh"; var iNum = Str.indexof ("C"); alert (iNum); Pop Up 2

6. Substring () Intercept string usage: substring (start,end) (not including end)

var sTr = "Abcdefghijkl"; var sTr2 = str.substring (3,5); var sTr3 = str.substring (1); alert (STR2); Eject Dealert (STR3); Eject BCDEFGHIJKL
String inversion
var str = ' asdfj12jlsdkf098 '; var str2 = Str.split ("). Reverse (). Join ("); alert (STR2);
The role of timer timers in JavaScript

1. Timed Call function
2. Making animations

Timer type and syntax
    /* Timer:    setTimeout only executes once timer     cleartimeout Turn off timer that executes only once    setinterval  repeatedly executed    Clearinterval Close the repeatedly executed timer */var time1 = setTimeout (myalert,2000); var time2 = SetInterval (myalert,2000);/*cleartimeout ( TIME1); clearinterval (time2); */function Myalert () {    alert (' ok! ');}
Variable scope

Variable scope refers to the scope of the variable, the variables in JavaScript are divided into global variables and local variables.

1. Global variables: Variables defined outside the function are common to the entire page and can be accessed both inside and outside the function.
2. Local variables: variables defined inside a function can only be accessed within the function that defines the variable, and cannot be accessed externally.

<script type= "Text/javascript" >    //define global variables    var a = n;    function Myalert ()    {        //define local variable        var b = all;        alert (a);        Modify the global variable        a++;        alert (b);    }    Myalert (); Popup 12 and    alert (a);  Popup        alert (b);  Error </script>
Closed function

A closed function is another way of writing an anonymous function in JavaScript, creating a function that executes at the outset without naming it.

General-defined functions and execution functions:

function Myalert () {    alert (' hello! ');}; Myalert ();
Closed function:
(function () {    alert (' hello! ');}) ();

You can also add "~" and "!" before the function definition and other symbols to define anonymous functions

!function () {    alert (' hello! ');} ()
function of the closed function

The closed function can create a separate space, the variables and functions defined within the enclosing function will not affect functions and variables with the same name, avoid naming conflicts, and add JS files in this way when multiple JS files are introduced on the page, such as:

var iNum01 = 12;function Myalert () {    alert (' hello! ');} (function () {    var iNum01 =;    function Myalert () {        alert (' Hello!world ');    }    alert (INUM01);    Myalert ()}) () alert (INUM01); Myalert ();

  

JavaScript on the front

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.