JS operation of HTML base

Source: Internet
Author: User
Tags script tag

HTML Basics of JS

The HTML of the three sharp-edged JS is also called JavaScript, look like a little connection with Java, in fact, he and Java have no relationship with half a dime, JavaScript and we learn Python, Go, Java, C + +, are a separate language, The Python interpreter has Python2.7, python3.x, and the browser has the function of explaining JavaScript, so it is one of the three tools of HTML.

In HTML, you can write Javascript/js code in head, wrapped by a script tag, and when the browser interprets the HTML, when it encounters a style tag, it is interpreted according to the CSS rules, and when it encounters a script tag, it is interpreted in accordance with the syntax rules of JavaScript.

Introducing JavaScript code, similar to the import of Python

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

Head the introduction of JS and the body in the introduction of JavaScript difference

HTML code from the top and bottom, if the introduction of JS in the head, affecting the speed of the page open, there is a risk, so usually placed at the bottom of the HTMLBody, so that the content of the page first displayed, and finally loading JS. Note: Write at the bottom to have a baseline, written in the body inside the bottom.

<! DOCTYPE html>
"en">
<meta charset="UTF-8">
<title>Title</title>
<!--<linkrel= "stylesheet" href= "Static" >--> # #linkcan introduce CSS
<style></style> # #加载其中的css样式
<!--write on the top and write the difference below:-->
<!--
affects page loading speed-
<!--<scriptsrc= "s1.js" type= "Text/javascript" ></script>--> # # # # #
Introducing JSand specify the type
<body>

<script>
//if (1 = = 2) {#through {}blocks of code to be split.
Console.log (1111111111) # # # # #
Print Results
} else if (2 = = 2) {
Console.log (1111111111)
} else {
Console.log ('
the last! ‘)
// }
//
if the two equals sign does not determine the type of dataIf the three equals sign determines the type of data
if (' 1 ' = = = ' 1 ') {
Console.log (1111)
} else {
Console.log (2222)
// }

Switch (1) {# # #
the incoming parameter one by one corresponds.
Case 1:
Console.log (111); ##
Notice that the semicolon is added to the different statements, and the front-end processing code is easy.
Break #break
It 's better to addOtherwise, the other case will be printed .Content.
Case 2:
Console.log (222);
Break
Default
Console.log (333);
// }

var name = ' Dsx nhy ';
For (var A in name) {
Console.log (Name[a]); ###
Circular angle mark, through the angle mark to take the value
// }
//
var list = ['
big bro ', 'Bull and Ox ', 'Uncle Ann '];
for (var i in list) {
Console.log (List[i]) ######
Loop array
// }
//
var dict = {'
BMW ': ' BMW ', 'Mercedes ': ' BC '};
for (var d in Dict) {
Console.log (d); ##
take key
Console.log (Dict[d]); ##
Take value
// }

//
a loop that does not support dictionaries
var list = ['
big bro ', 'Bull and Ox ', 'Uncle Ann '];
for (vari=0;i<=list.length;i++) {
Console.log (List[i] # # # #
cyclic numbers, printingcan only loop listand string
// }

//
with PythonSame
while (1==1) {
Console.log (1111) # #
dead Loop
// }

Js the functions in

Common functions
function f (name,age) {# # #
through functions
Console.log (name);
Console.log (age);
// }
F (' Dsx ', 18)


function f () {
Console.log (' in ' +name)
// }
Console.log (' Out ' +name);
F ()

self-executing functions
A= (function () {
Console.log (' self-
executing function! ‘)
// });
A ()

</script>
</body>

Binding events

<! Doctypehtml>

<meta charset= "UTF-8" >

<title>Title</title>

<body>

<div>

<input id= ' i1 ' type= "button" value= "one-key input username" >

</div>

<div>

<input type= "text" name= "username" >

</div>

<script>

Enter houyafan into the input box when the button is clicked

function Demo (ths) {# # #绑定后 (such as through the onclick binding function) ths represents the label.

Ths.parentElement.nextElementSibling.lastElementChild.value = ' 222 '

// }

var demo =document.getelementbyid (' I1 ');

Demo.onclick = function () {# # #当点击的时候再绑定 anonymous functions

Demo.parentElement.nextElementSibling.lastElementChild.value = ' 222 ';

}

</script>

</body>

Object-Oriented Programming

<! Doctypehtml>
"en">
<meta charset="UTF-8">
<title>Title</title>
<body>


<script>
//function f (name) {
THIS.name = name; ###
classwith thisuse related (equivalent to PYthe class in
This.say = function () {
Console.log (' say--> ' +this.name)
//    }
// }
var obj = new F (' DSX '); ##
instantiation ofInvokes the instantiation method.
Console.log (Obj.name);
Obj.say ()




function f (name) {
THIS.name = name;
This.say = function () {
Console.log (THIS.name)
//    }
// }
//
var obj = new F (' DSX ');
Console.log (Obj.name);
Obj.say ()

Class F ():
def __init__ (name):
Self.name= Name
Def say (self):
Print (Self.name)

obj = f (' DSX ')

Obj.name

</script>
</body>

2.js related Operations

Comments

Single-line comment via//Multiline pass/* */

JS variables

name = ' DSX '; Default global variables

function func () {

var name = ' Niulaoshi '; Local variables

}

JS basic Data type (JavaScript declaring data type through new )

on the console Operation

String

Defining strings

var str = ' You're happy! ‘;

var name = ' Big bro ';

Concatenation of strings

var name_str = name+str; # # #直接可通过加号拼接

String manipulation

str = ' big bro '

Str.charat (0) Get a character char character from a string according to a corner mark

Str.substring (1,3) Gets the string sub-sequence greater than or equal to x less than y according to the corner label

Str.length Get string length

Str.concat (' Professor Niu ') stitching strings with plus sign stitching

Str.indexof (' master ') gets the position of the subsequence and only takes the first match

Str.slice (0,1) slice start end

Str.tolowercase () changed to lowercase

Str.touppercase () Change capitalization

Str.split (' division ', 1) slice returns the array parameter 2 for the first x elements of the array after the split

Numeric type (JavaScript has only one numeric type.) Numbers can be with decimal points or without)

var age = 18;

var score = 89.22;

Number = ' 18 ';

String goto

var n = parseint (number); If it is a decimal, the number after the decimal point is removed.

Convert to Decimal

F =parsefloat (number)

Boolean type (TRUE or FALSE)

var t = true; var f = false;

Array type (which is the list of Python)

 

//First way to create var list = new Array ();

List[0] = ' big bro ';

List[1] = ' Professor Niu ';

 

//second method of creation

var list2 = new Array (' Big bro ', ' Professor Niu ');

 

//third method of creation

var list3 = [' Big bro ', ' Professor Niu '];

 

Array Operations

var list3 = [' Big bro ', ' Professor Niu '];

 

List3.length length of array

 

List3.push (' dsx ') tail chase parameters

 

List3.shift () gets an element in the head and deletes the element

 

List3.pop () tail gets an element and deletes the element

 

List3.unshift (' DSX ') inserts a data header

 

List3.splice (Start, DeleteCount, value) inserts, deletes, or replaces elements of an array    intermediate 0 to insert

 

List3.splice (N,0,val) specifies the position of the insertion element

 

List3.splice (N,1,val) specifies the position substitution element

 

List3.splice (n,1) to specify a location to delete an element

 

List3.slice () slices;

 

List3.reverse () inversion

 

List3.join ('-') to stitch the array into a string based on the delimiter

 

List3.concat ([' abc ']) array and array concatenation

 

List3.sort () sort

Object type (equivalent to a Python dictionary)

var dict = {name: ' Dsx ', age:18,sex: ' Male '};

var age = Dict.age;

var name = dict[' name '];

Delete dict[' name '] deleted

Delete Dict.age Remove

Timer

SetInterval (Alert (' Big bro '), 5000); Parameter 1 is the function performed by the timer, and the second parameter is the time interval of the timer to work in milliseconds

function T1 () {

Console.log (' I am big bro ')

}

SetInterval (' T1 () ', 5000);//Can run method

JS Conditional Judgment Statement

if (condition) {

Execute code block

} else if (condition) {

Execute code block

} else {

Execute code block

};

if (1 = = 1) {

Console.log ()

} else if (1! = 1) {

Console.log ()

} else if (1 = = = 1) {

Console.log ()

} else if (1!== 1) {

Console.log ()

} else if (1 = = 1 && 2 = = 2) {//and

Console.log ()

} else if (1 = = 1 | | 2 = = 2) {//or

Console.log ()

}

Switch (a) {

Case 1:

Console.log (111);

Break

Case 2:

Console.log (222);

Break

Default

Console.log (333)

}

JS Looping Statements

The first kind of loop

The loop is the angle mark

TMP = [' BMW ', ' Mercedes ', ' Nissan '];

TMP = ' BMW Mercedes-Benz Nissan ';

TMP = {' BMW ': ' BMW ', ' Mercedes ': ' BC '};

for (var i in TMP) {

Console.log (Tmp[i])

}

The second kind of loop

A loop that does not support dictionaries

for (var i = 0; i < i++) {

Console.log (Tmp[i])

}

The Third Kind of loop

while (1 = = 1) {

Console.log (111)

}

function definition

1. Common functions

Function name (formal parameter, formal parameter, formal parameter) {

Execute code block

}

Function name (formal parameter, formal parameter, formal parameter);

2, anonymous function anonymous function does not have a name, cannot be called when found, the entire function as a parameter passed

SetInterval (function () {

Console.log (11)

}, 5000);

3. Self-executing function creates function and executes automatically

When the introduction of multiple JS files, the function name may be duplicated, then through the self-executing function, to ensure that each JS file will be parsed, resulting in a separate container to prevent the call conflict

(function (name) {

Console.log (name)

}) (' Dsx ');

Scope

The scope of Python is scoped by functions, and other languages are scoped with code blocks ({}).

JavaScript is scoped as a function

function tmp () {

var name = ' DSX ';

Console.log (name)

}

TMP ();

Console.log (name);

2. The function scope has been created before the function is called.

var name = ' Nhy ';

function A () {

var name= ' dsx ';

Function B () {

Console.log (name);

}

Return b

}

var C = A ();

C ();

3. The scope of the function exists in the scope chain (when the code does not execute, Mr. into the scope chain)

When a function is nested, each function is a scope, and multilayer is called a scope chain, looking for a rule that follows the scope chain

function outer () {

name = ' nn ';

function inner () {

var name = ' II '

Console.log (' in ', name)

}

Console.log (' Out ', name);

Inner ()

}

Outer ();

When a function is not called, only the scope is generated, and when the call follows the scope chain execution, name is HHH

function outer () {

var name = ' nn ';

function inner () {

Console.log (' in ', name)

}

var name = ' HHH ';

Console.log (' Out ', name);

Inner ()

}

Outer ();

4, within the function, the local variables in advance declaration of JavaScript function before running will find all local variables within the function execution

var xxx;

function func () {

Console.log (name);

var name = ' DSX ';

}

Func ();

Object oriented

In JavaScript, methods are similar to classes in that they differ in whether they have this, and if so, they can be used as classes.

The JavaScript class has the Python constructor by default __init__

function Foo (name) {

THIS.name = name;

}

JavaScript needs to use the New keyword to create objects when creating objects

var obj = new Foo (' dsx ');

Console.log (Obj.name);

A method is defined in a class, although it can be used, but there are duplicate instance methods in multiple instances, wasting resources

When creating an object, say creates a say method each time the object is created.

function Foo1 (name) {

THIS.name = name;

This.say = function () {

Console.log (THIS.name)

}

}

var obj1 = new Foo1 (' dsx_obj1 ');

Obj1.say ();

Refine the definition of a class

function Foo2 (name) {

THIS.name = Name

}

Class of the prototype, the common method is extracted, when the instantiation, only created an object called Foo2, the object is only name, in the call method to the current Foo in the search, not found, will be in the prototype to find

Whether the method is available. There is execution, there is no error

Foo2.prototype = {

Say:function () {

Console.log (THIS.name)

}

};

var obj2 = new Foo2 (' dsx_obj2 ');

Obj2.say ();

Serialization of

1

2

Json.stringify (obj) serialization

Json.parse (str) deserialization

Escape

Escape Chinese or special characters

1, in the standard URL specification is not allowed to appear in Chinese characters or some special characters, so to be escaped

2, & represents the link of the parameters, if you want to pass & to the backend then must be escaped

Characters that are not escaped from the decodeURI (URL) URL

decodeURIComponent (URL) URI component of an escaped character

Escape characters in the encodeURI (URL) URI

encodeURIComponent (URL) escapes the characters in the URI component

String escape

var name= ' big bro '

Escape (name) escapes the string

Unescape (name) escape string decoding

JS operation of HTML base

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.