Introduction to JavaScript

Source: Internet
Author: User
Tags closure script tag

Javascript:


The way JavaScript embeds pages


1. Inter-row events (mainly for events)
<input type= "button" Name= "onclick=" alert (' ok! ‘);" >
2. Page Script Tag embedding
<script type= "Text/javascript" >
var a = ' Hello! ‘;
alert (a);
</script>
3. External Introduction
<script type= "Text/javascript" src= "Js/index.js" ></script>



Second, comments and variables:


1, single-line comment://

2. Multi-line Comment:/* */

3. Variables:
#弱类型语言, the type is determined by the value
var a = 123,b = ' abc ';
#变量类型:
Number, String, Boolean, undefined (variable defined, not assigned), NULL
Composite type: Object

Third, get elements and operation elements:

1. The '-' in the attribute does not appear in the script notation, instead of the hump type.
2, Special: When you operate the class attribute, use classname.
3, through the [] way can write variables.
4, through the innerHTML can read and write elements wrapped content.

 #demo1: Manipulating elements
<! DOCTYPE html>

<meta charset= "UTF-8" >
<title> operating Elements </title>
<script type= ' Text/javascript ' >
Window.onload = function () {
document.getElementById (' Div1 '). title = ' What a nice day ';
var odiv = document.getElementById (' Div1 ');
ODiv.style.color = ' red ';
oDiv.style.fontSize = ' 30px ';

var attr = ' background ';
odiv[' style '][attr] = ' gold ';

alert (odiv.innerhtml);
}
</script>

<body>
<input type= ' button ' name= ' value= ' tank ' onclick= ' alert (' hello! ') ' >
<div id= ' div1 ' title= ' What a fuking day! ' > This is an element </div>

</body>

  #demo2换肤
<! DOCTYPE html>

<meta charset= "UTF-8" >
<title> Skin Changing </title>
<style type= ' text/css ' >
. box1{
width:200px;
height:200px;
Background-color:gold;
}

. box2{
width:200px;
height:200px;
background-color:red;
}
</style>
<script type= ' Text/javascript ' >
Window.onload = function () {
document.getElementById (' Btn01 '). onclick = Skin01;
document.getElementById (' btn02 '). onclick = skin02;

}
function Skin01 () {
document.getElementById (' link '). className = ' box1 ';
}
function Skin02 () {
document.getElementById (' link '). className = ' Box2 ';
}
</script>

<body>

<input type= ' button ' name= ' value= ' skin 1 ' id= ' Btn01 ' >
<input type= ' button ' name= ' value= ' Skin 2 ' id= ' btn02 ' >
<div class= ' box1 ' id= ' link ' ></div>

</body>


Iv. Anonymous functions


#伪代码
Window.onload = function () {
var odiv = document.getElementById (' Div1 ');
/*odiv.onclick = Myalert;
function Myalert () {
Alert (' OK ');
}
*/
Odiv.onclick = function () {
Alert (' OK ');
}
}
<body>
<div id= ' div1 ' > tags </div>
</body>

Switch multiple judgment statements, followed by the value of the variable.


var today = 2;
Switch (today) {
Case 1:
Alert (' mathematics ');
Break
Case 2:
Alert (' language ');
Break
Case 3:
Alert (' foreign language ');
Break
Default
Alert (' no tuition ');
}


Six, array

We recommend that you use the second method of creation
var = new Array (ARR1);
var aRr2 = [' A ', ' B ', ' C '];


1. Join
var sTr = arr2.join ('-');
2, Add/Remove elements, Push/pop usage consistent
#这里是从前面增/Delete
Arr2.unshift (0);
Arr2.shift ();
3. Inverse array
Arr2.reverse ();
4. Splice also add delete element
#括号里分别是从第几个元素开始, delete a few, add elements.
Arr2.splice (2,1,6,7,8);
5. Get Elements through tags
document.getElementsByTagName (' element name ');
6. For loop
for (i=0;i<n;i++) {}

7, the array to remove weight:
var aRr = [1,3,5,7,3,3,2,6,45,2,6,3,2];
var aRr2 = [];
for (Var i=0;i<arr.length;i++) {
if (Arr.indexof (arr[i]) = = i) {
Arr2.push (Arr[i]);
}
}



Vii. composition of JavaScript


1. ECMAscript JavaScript syntax (variables, functions, looping statements, etc.)
2. DOM Document Object Model how to manipulate HTML and CSS
3. Some methods of the BOM browser object model Operation browser



Eight, string processing method


1. String merge operation: "+"
2. parseint () converts a numeric string to an integer
3. parsefloat () converts a numeric string to a decimal number
#小数计算bug, results are not allowed:
var a = 0.1;
var B = 0.2;
Alert (parsefloat (a) + parsefloat (b));
#解决方法:
Alert ((Parsefloat (a) *100 + parsefloat (b) *100)/100);
4. Split () separates a string into an array of strings
5, CharAt () gets a character in a string
6, IndexOf () find whether the string contains a character, not found return-1
7. Substring () Intercept string usage: substring (start,end) (not including end)
8. toUpperCase () string to uppercase
9, toLowerCase () string Turn lowercase
10. String Inversion:
var sTr = ' 12435235dxcfzxcvom45634 ';
var sTr2 = Str.split ("). Reverse (). Join (');



Nine, the method of debugging program


1. Alert
2, Console.log
3, Document.title

#parseInt and parsefloat cannot correctly Judge Nan, you can use isNaN
#demo: Calculators
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title> Calculators </title>
<script>
Window.onload = function () {
var oInput1 = document.getElementById (' input01 ');
var oInput2 = document.getElementById (' input02 ');
var obtn = document.getElementById (' btn ');
var osel = document.getElementById (' sel ');

Obtn.onclick = function () {
var num1 = Oinput1.value;
var num2 = Oinput2.value;
var cal = Sel.value;

if (num1== ' | | num2== ') {
Alert (' Input box cannot be empty ');
Return
}
if (IsNaN (NUM1) | | IsNaN (NUM2)) {
Alert (' Only enter numbers! ‘);
Return
}

Switch (CAL) {
Case ' + ':
Alert ((parsefloat (NUM1) *100+parsefloat (num2) *100)/100);
Break
Case '-':
Alert ((parsefloat (NUM1) *100-parsefloat (num2) *100)/100);
Break
Case ' * ':
Alert (((parsefloat (NUM1) *100) * (parsefloat (num2) *100))/10000);
Break
Case '/':
Alert ((parsefloat (NUM1) *100)/(parsefloat (num2) *100));
Break
}
}
}
</script>
<body>
<input type= ' text ' name= ' id= ' input01 ' >
<select id= ' sel ' >
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type= ' text ' name= ' id= ' input02 ' >
<input type= ' button ' name= ' value= ' calculation ' id= ' btn ' >
</body>


Ten, timer

  1. Demo Timed frame pseudo code

<script>
Window.onload = function () {
var oPop = document.getElementById (' Pop ');
var Oshut = document.getElementById (' shut ');
function Showpop () {
OPop.style.display = ' block ';
}
SetTimeout (showpop,3000);

Oshut.onclick = function () {
OPop.style.display = ' None ';
}
}
</script>


 2. Turn off the timer:
var timer = setTimeout (function () {alert (' hello ');},3000);
Cleartimeout (timer);


 3, repeated timer:
var timer2 = setinterval (function () {alert (' Hi ');},2000);

  4, Demo countdown Pseudo-code:
<script type= "Text/javascript" >
Window.onload = function () {
var odiv = document.getElementById (' Div1 ');
function Timeleft () {
var now = new Date ();
var future = new Date (2020,1,1,0,0,0);
var lefts = parseint ((future-now)/1000);
var day = parseint (lefts/86400);
var hour = parseint (lefts%86400/3600);
var min = parseint (LEFTS%86400%3600/60);
var sec = lefts%60;
str = ' 0 o'clock ' +day+ ' +hour+ ' +min+ ' ' +sec+ ' seconds away from the day of January 1, 2020;
odiv.innerhtml = str;
}
Timeleft ();
SetInterval (timeleft,1000);
}

</script>
......
<div id= "Div1" ></div>


Xi. closed function and closure

1, enclosing function
(function () {
var odiv = document.getelement Byid (' Div1 ');
ODiv.style.color = ' red ';
}) ();

#还可以在函数定义前加上 "~" and "!"    such as symbols to define anonymous functions
!function () {
var odiv = document.getElementById (' Div1 ');
ODiv.style.color = ' red ';
} ()

2, Closure:
Function nesting functions, intrinsic functions can refer to parameters and variables of external functions, parameters and variables are not reclaimed by garbage collection mechanism


  #闭包用处
  2-1, a variable is stationed in memory for a long time, can be used in the loop to save the index value
<script type= "Text/javascript" >
Window.onload = function () {
var aLi = document.getelementsbytagname (' li ');
for (Var i=0;i<ali.length;i++)
{
(function (i) {
Ali[i].onclick = function () {
alert (i);
}
}) (i);
}
}
</script>
......
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
</ul>

  2-2, private variable counter, external inaccessible, avoid the pollution of global variables
<script type= "Text/javascript" >

var count = (function () {
var a = 0;
function Add () {
a++;
return A;
}
return add;
})()

Count ();
Count ();
var nowcount = count ();
alert (Nowcount);

</script>


12. Built-in objects:


  1. Document

Document.referrer//Get the address of the previous Jump page (requires server environment)
  2. Location

Window.location.href//Get or reset URL address
Window.location.search//Get Address Parameters section
Window.location.hash//Get page anchor point or hash value
  3. Math

Math.random get a random number of 0-1
Math.floor Downward rounding
Math.ceil rounding up


    Demo randomly takes 10 integers from 10 to 20
<script>
var a = 10;
var B = 20;

var arr = [];

for (Var i=0;i<10;i++) {
var num = Math.floor (Math.random () * (b-a+1) +a);
Arr.push (num);
}

Alert (arr);
</script>


13. Object-Oriented design


  1. Monomer
<script type= "Text/javascript" >
var Tom = {
Name: ' Tom ',
Age:18,
Showname:function () {
Alert (' My name is ' +this.name ');
},
Showage:function () {
Alert (' I'm ' +this.age+ ' this year ');
}
}
</script>

 2. Factory mode
<script type= "Text/javascript" >
function Person (name,age,job) {
var o = new Object ();
O.name = name;
O.age = age;
O.job = job;
O.showname = function () {
Alert (' My name is ' +this.name ');
};
O.showage = function () {
Alert (' I'm ' +this.age+ ' this year ');
};
O.showjob = function () {
Alert (' My job is ' +this.job ');
};
return o;
}
var tom = person (' Tom ', 18, ' Programmer ');
Tom.showname ();

</script>

   3. Constructor function
<script type= "Text/javascript" >
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.showname = function () {
Alert (' My name is ' +this.name ');
};
This.showage = function () {
Alert (' I'm ' +this.age+ ' this year ');
};
This.showjob = function () {
Alert (' My job is ' +this.job ');
};
}
var tom = new Person (' Tom ', 18, ' Programmer ');
var jack = new Person (' Jack ', 19, ' Sales ');
alert (tom.showjob==jack.showjob);
</script>

  4, prototype mode, the realization of the same object common method
<script type= "Text/javascript" >
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
}
Person.prototype.showname = function () {
Alert (' My name is ' +this.name ');
};
Person.prototype.showage = function () {
Alert (' I'm ' +this.age+ ' this year ');
};
Person.prototype.showjob = function () {
Alert (' My job is ' +this.job ');
};
var tom = new Person (' Tom ', 18, ' Programmer ');
var jack = new Person (' Jack ', 19, ' Sales ');
alert (tom.showjob==jack.showjob);
</script>

   5. Inheritance
#call and apply: You can change the point of this to inherit properties.
#方法继承: Assigns an instance of the parent class to the child class's prototype property.
<script type= "Text/javascript" >

function Fclass (name,age) {
THIS.name = name;
This.age = age;
}
Fclass.prototype.showname = function () {
alert (this.name);
}
Fclass.prototype.showage = function () {
alert (this.age);
}
function Sclass (name,age,job)
{
Fclass.call (This,name,age);
This.job = job;
}
Sclass.prototype = new Fclass ();
Sclass.prototype.showjob = function () {
alert (this.job);
}
var tom = new Sclass (' Tom ', 19, ' full stack engineer ');
Tom.showname ();
Tom.showage ();
Tom.showjob ();
</script>


Introduction to JavaScript

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.