1, ECMAScript of JS
(1) Data type
There are also many data types in JS, which can be divided into basic data types and reference data types.
1. Basic data type:
(1) Undefined:Undefined type has only one value, undefined. When a declared variable is uninitialized, the default value of the variable is undefined.
(2) Null: there is only one value, that is, null means empty and a placeholder. The value undefined is actually derived from the value null, so ECMAScript lists them as equivalent.
For example: Alert (null = = undefined)// true
Although the two values are equal, they represent different meanings. Null is a null value,
Undefined is undefined.
(3) Boolean: indicates true or false. There are only two values: true and false.
(4) Number: represents any number. In JS, all value types are collectively referred to as number types.
(5) String: the string type is assigned with single quotation marks or double quotation marks.
2. Reference type:
Reference types are often called class es. JavaScript converts reference types into objects for processing.
JavaScript is object-based rather than object-oriented. The default value of the object is null.
We can view the data type of a variable through typeof (variable name).
(2) Variable
Naming syntax: VAR variable name = initial value; Or var variable; Var variable 1, variable 2, variable 3;
Code example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js Variable declaration for</title> </head> <body> </body> <script type="text/javascript"> var name = "one's junior of equal standing"; var age = 18; var height = 150.5; var isBoy = false; var boyFriend = { "name": "Yang Ning", "age": 38 }; var son = null; var daughter; var hobby = function() { console.log("unremittingly~"); } console.log(name); console.log(age); console.log(height); console.log(isBoy); console.log(boyFriend);(6) Operator console.log(son); console.log(daughter); console.log(hobby); </script> </html>
design sketch:
(3) Operator
1. Unary operators: + +, --: when the symbol comes first, increase (decrease) and then operate; After the symbol, it is calculated first, and then increased (decreased) by itself
2. Arithmetic operators:+ - * / % ++ -- Wait.
3. Assignment operator:= += -= *= /= %= Wait.
4. Comparison operators: >, <, > =, < =, = =,! ==== (congruent),! = =: The same type is directly compared, and different types are converted first and then compared.
5. Logical operators: & & (short circuit and), | (short circuit or)! (non)
6. Conditional (ternary) operator: expression? Value 1: value 2 (the expression is true, value 1, and the expression is false, value 2)
The use of all the above operators is similar to java.
(4) Process control
Similar to java, not much description
(5) Basic object
1. Function function object
1. Syntax format of creation method:
(1) Var func = new function (formal parameter list, method body);
(2) function method name (formal parameter list) {method body} (recommended);
(3) var method name = function (formal parameter list) {method body};
2. Syntax format of method call:
Method name (actual parameter list);
3. js method features:
(1) When defining a method, the formal parameter type and the return value type are not written
(2) Method is an object, and the same method name defined will be overwritten
(3) In JS, the call of a method is only related to the method name and has nothing to do with the method parameters
4. js method attribute: length, used to get the number of actual parameters
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function demo(){ console.log("Function declaration...."); } function demo(a,b){ console.log("Function declaration"+a+b); } demo(); //Parametric function function demo01(a,b){ console.log(a+b); } demo01(1,2); function demo02(a,b){ return a+b; } console.log(demo02(10,20)); //Anonymous function var fn = function(){ console.log("Anonymous function"); } fn(); </script> </head> <body> </body> </html>
2. Array object
1. Create array:
(1)var arr = new Array(); Empty array
(2) Var arr = new array (default length) array of default length
(3) var arr = [element list]; Array with initial value
2. js array features:
(1) In JS, the type of array elements is variable
(2) In JS, the length of the array is variable
3. js array attribute: length gets the length of the array and the number of elements
4. Common methods in js array:
(1) Join (character); Concatenates array elements into a string with the specified characters
(2)push(); Adds one or more elements to the end of the array and returns the new length
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> var arr = new Array(); console.log(arr); var arr1 = new Array(3); console.log(arr1); var arr2 = [12,"hello",true]; console.log(arr2); //Assign a value to an array arr[0] = 120; console.log(arr); //Add directly to the end arr2.push("Hello"); </script> </head> <body> </body> </html>
3. Boolean (understand)
① Consistent with java, true/false
② Define variables of type boolean
var b = true/false;
4. Date Date object
1. Create date object: var now = new Date() gets the current time.
2. Common methods for date objects:
(1) toLocaleString(): converts the Date object into a string according to the local time format.
(2) getTime(): returns the number of milliseconds since January 1, 1970
(3) getHours(): returns the number of hours.
(4) getMinutes(): returns the number of minutes.
(5) getSeconds(): returns the number of seconds.
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> var d = new Date(); console.log(d); //Time formatting console.log(d.toLocaleString()); console.log(d.toLocaleDateString()); console.log(d.toLocaleTimeString()); console.log(d.getFullYear); console.log(d.getMonth()+1); console.log(d.getDate()); console.log(d.getHours()); </script> </head> <body> </body> </html>
5. Math Math object
1. Create: Math objects can be used directly without creating them. Call the method directly when using,
For example: Math. Method name ();
2. Common methods:
(1) random(): returns a random number between 0 and 1
(2) max(x,y): returns the maximum of X and y
(3) min(x,y): returns the lowest of X and y
(4) ceil(x): round up the logarithm
(5) floor(x): round the logarithm down
(6) round(x): rounds the number to the nearest integer
(7) abs(x): returns the absolute value of the number
3. Attribute: Pi, PI
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js Mathematical objects in Math</title> </head> <body> </body> <script type="text/javascript"> console.log(Math.random());//random number console.log(Math.max(10, 20));//Maximum console.log(Math.min(10, 20));//minimum value console.log(Math.ceil(5.5));//Round up console.log(Math.floor(5.5));//Round down console.log(Math.round(5.5));//rounding console.log(Math.abs(-10));//absolute value console.log(Math.PI);//PI </script> </html>
6. Number number object
1. JavaScript has only one numeric type. Numbers can be with or without a decimal point, representing integers and decimals
2. Define numeric type
var n = 10;
var n = 10.34;
7. String string object
1. Create:
(1)var str1 = "abc"; // string
(2)var str2 = new String("abc"); // object
2. Common methods:
(1) Gets the length of the string str1.length
(2) Whether to start with a character startsWith()
(3) Whether to end with a character endsWith()
(4) Intercept string
a. Substring (start subscript, end subscript)
b. Substr (start subscript, intercept length)
(5) Splits a string according to a character and returns the array split()
Example code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> var str="Hello World!"; console.log(str.length); console.log(str[2]); //common method console.log(str.startsWith("He")); console.log(str.endsWith("!")); console.log(str.indexOf("l")); console.log(str.lastIndexOf("W")); console.log(str.substring(0,6)); console.log(str.substr(0,6)); console.log(str.split(" ")); </script> </head> <body> </body> </html>
8. RegExp regular expression object
1. Single character: for example, [a], [ab] matches a or b, [a-zA-Z0-9] matches letters or numbers [characters]
2. Metacharacter: \ d represents a number
3. Quantifier symbol:
?: Indicates 0 or 1 occurrences
*: Indicates 0 or more occurrences
+: Indicates one or more occurrences
{m} M occurrences
{m,} occurs at least m times
{m,n}: means M = < quantity < = n
4. Start end symbol:
^ start
$ end Extend [^ abc]
5. To create a regular expression object:
(1) var reg = new RegExp("regular expression");
(2) var reg = / regular expression /;
6. Methods to test regular validation:
Test (parameter): verify whether the specified string conforms to the specification of the regular definition
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> var reg = new RegExp("[abc]"); var reg1=/a/; console.log(reg.test("a")); var reg3 = /^1[3456789]\d{9}$/ if(reg3.test("12345678998")){ console.log("cell-phone number"); }else{ console.log("Not a cell phone number"); } </script> </head> <body> </body> </html>
9. Global object
1. Global encapsulated methods can be called directly without objects. Method name ();
2. Common methods:
(1) encodeURI(): encodes a string as a URI
(2) decodeURI(): decodes an encoded URI
(3) encodeURIComponent(): encodes a string as a URI component
(4) decodeURIComponent(): decodes an encoded URI component
(5) parseInt(): parses a string and returns an integer. Judge whether each character is a number one by one until it is not a number. Change the previous number to number
(6) isNaN(): check whether a value is a number. false is a number and true is not a number
(7) eval(): evaluates the JavaScript string and executes it as script code
Code example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Global Global object</title> </head> <body> </body> </html> <script> var uri ="http://xue.ujiuye.com/foreuser/login/login_url/http%3A%2F%2Fxue.ujiuye.com%2F/"; //Encode the string as a URI var encodeUri = encodeURI(uri); console.log(encodeUri); //Decode an encoded URI var decodeUri = decodeURI(encodeUri); console.log(decodeUri); //Encodes a string as a URI component var enUriCom = encodeURIComponent(uri); console.log(enUriCom); //Decode an encoded URI component var deUriCom = decodeURIComponent(enUriCom); console.log(deUriCom); var str = "10"; //Convert str to int var i = parseInt(str); console.log(i);//10 //Detects if i is a non numeric type console.log(isNaN(i));//false //Find the square of i console.log(eval(i * i));//100 </script>
2, DOM object
(1) Introduction to DOM
1. Document Object Model (DOM) is a standard programming interface recommended by W3C to deal with extensible markup language. Through HTML DOM, JavaScript can access and change all elements of HTML documents.
2. When a web page is loaded, the browser creates a document object model of the page
(Document Object Model).
dom principle: if the document and all the tags in the document are regarded as objects, the attributes in the tag are the attributes of the object, so we can use this when obtaining or setting the tag attributes
Object. Attribute name (get the corresponding attribute value of a tag) or object. Attribute name = XXX (set value or modify value for the tag's attribute). If you modify or get the content of the tag, you can implement the object through innerHTML, innerText,value and other attributes. InnerHTML (get the tag content, including the tag and style inside the tag) object. InnerText (get the plain text in the label, excluding the label and style inside the label)
The above two properties are used when obtaining the closed label content
---------------------------
Object. Value (get the value of the tag, form tag)
It is used when obtaining the content or value of a single label
(2) Get page element object
1. How to find page elements:
(1) document.getElementById(id): finds an element by its id number. Returns a single object
(2) document.getElementsByTagName(name): finds an element by tag name. Returns an array object
(3) document.getElementsByClassName(name): find elements by class name. Return array object
(4) document.getElementsByName(name): finds an element by name attribute. Returns an array object
2. In the above four methods, because the id number of elements in the page is unique, the number of elements obtained through id is also unique; while the number of elements obtained by the other three methods is not unique, so you need to obtain the specified elements like an array.
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #d{ } </style> </head> <body> <div id="d" class="c">Catch ducks, catch a few <a href="">Start catching</a> </div> <p class="c">Quack, quack, quack</p> </body> <script> //Gets the label object with id attribute d var obj = document.getElementById("d"); console.log(obj); //Get label content console.log(obj.innerHTML); console.log(obj.innerText); console.log("============================="); var objArray = document.getElementsByClassName("c"); //Traversal array for(var i = 0;i<objArray.length;i++){ console.log(objArray[i].innerHTML); } </script> </html>
(3) Operation page element object
1. Create a dom object
document.createElement("tag name");
2. Add dom object
(1) A.appendChild(B) add B to the back of A
(2) A. insert before (B, c) add B to the front of C inside a
3. Delete dom object
(1) A.remove() deletes a
(2) A.remove(B) delete B inside a
4. Replace dom object
A.replaceChild(B, C) replaces C inside a with B
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function demo(){ var aObj = document.createElement("a"); //Add a tagger object herf attribute aObj.href = ""; //Add content aObj.innerHTML="use Baidu Search"; //Get ul object var ulObj = document.getElementsByTagName("ul")[0]; ulObj.appendChild(aObj); } function demo1(){ var iObj = document.createElement("img"); iObj.src="1.jpg"; iObj.width="500"; var ulObj = document.getElementsByTagName("ul")[0]; var liObj = document.getElementsByTagName("li")[1]; ulObj.insertBefore(iObj,liObj); } //Delete the first li tag function demo2(){ var liObj = document.getElementsByTagName("li")[0]; liObj.remove(); } function demo3(){ var liObj = document.getElementsByTagName("li")[0]; var ulObj = document.getElementsByTagName("ul")[0]; ulObj.removeChild(liObj); } function demo4(){ var aObj = document.createElement("a"); //Add a tagger object herf attribute aObj.href = ""; //Add content aObj.innerHTML="use Baidu Search"; var liObj = document.getElementsByTagName("li")[1]; var ulObj = document.getElementsByTagName("ul")[0]; ulObj.replaceChild(aObj,liObj); } </script> </head> <body> <ul> <li>First list item</li> <li>Second list item</li> <li>Third list item</li> </ul> <input type="button" value="add to" onclick="demo()"> <input type="button" value="External addition" onclick="demo1()"> <input type="button" value="Self deletion" onclick="demo2()"> <input type="button" value="He deleted" onclick="demo3()"> <input type="button" value="replace" onclick="demo4()"> </body> </html>
(4) Action element properties
1. Page element. Attribute name = "value" 2. Setting: label object. setAttribute("attribute name", "attribute value");
3. Get: tag object. getAttribute("attribute name");
4. Delete: label object. removeAttribute("attribute name");
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .c{ border: 1px solid red; height: 200px; width: 200px; border-radius: 50%; background-color: blue; } </style> <script> function demo(){ var divObj = document.getElementsByTagName("div")[0]; divObj.setAttribute("class","c"); divObj.setAttribute("style","background-image:url(1.jpg)"); var imgObj = document.getElementsByTagName("img")[0]; imgObj.setAttribute("title","Spider-Man"); } //Gets the src property of the img tag object function demo1(){ var imgObj = document.getElementsByTagName("img")[0]; console.log(imgObj.getAttribute("src")); } //Delete background picture for div function demo2(){ var divObj = document.getElementsByTagName("div")[0]; divObj.removeAttribute("style"); } </script> </head> <body> <div></div> <img src="1.jpg" width="300px" alt=""> <input type="button" value="Button" onclick="demo()"> <input type="button" value="get attribute" onclick="demo1()"> <input type="button" value="delete" onclick="demo2()"> </body> </html>
(5) Action element style
1. Direct operation
Page element. style.css style name = "value"
2. Indirect operation: operate by class name
Page element. setAttribute("class", "class name 1, class name 2")
First, define the css style in the class, and set the class for it through the inter line attribute class
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ border: 1px solid red; width: 300px; height: 300px; } </style> <script> function demo(){ var divObj = document.getElementsByTagName("div")[0]; divObj.style.backgroundColor="red"; divObj.style.color="green"; } </script> </head> <body> <div> This is a box </div> <input type="button" value="Add style" onclick="demo()"> </body> </html>
(6) Content of operation element
1. Tag object. innerHTML gets or sets that the content can contain tags
2. The tag object. innerText gets or sets that the content contains only text
3. The input tag object. value gets or sets the content in the input box
4. innerText and innerHTML syntax:
Get: tag object. innerHTML
Modify: tag object. innerHTML = value to modify
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function demo(){ var inObj = document.getElementsByName("username")[0]; var t = inObj.value; var reg = /^[a-zA-z0-9_$]{5,10}$/ var spanObj = document.getElementById("nameMsg"); if(reg.test(t)){ spanObj.innerHTML="<font color='green'>The user name is correct</font>"; }else{ spanObj.innerHTML="<font color='red'>Incorrect user name</font>"; } } </script> </head> <body> user name: <input type="text" name="username" id=""> <span id="nameMsg"></span><br><br> <input type="button" value="click" onclick="demo()"> </body> </html>
(7) Events
1. Element is used to perform some operation and trigger some code
2. How to bind events for page element objects
(1) Specify the attribute of the event in the tag: < button id = "BTN" ο Nclick = "func01()" > Click me < / button >
You need to define func01 in the script first~
(2) Get tag element binding event:
document.getElementById("btn").onclick =function(){}
The second binding event uses anonymous functions, which can be written directly into the method body code
3. Common events
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function demo(){ console.log("Get focus"); } function demo1(){ console.log("Lose focus"); } function demo2(){ console.log("Mouse in"); } function demo3(){ console.log("Mouse out"); } function demo4(){ console.log("Keyboard press"); } function demo5(){ console.log("Keyboard release"); } function demo6(){ console.log("Double click the event"); } </script> </head> <body> <div>div region</div> <select name="" id="d1"></select> <input type="text" name="" onfocus="demo()" onblur="demo1()" onkeydown="demo4()" onkeyup="demo5()" id=""> <div style="border: 1px solid red;height: 300px;width: 300px;" onmouseover="demo2()" onmouseout="demo3()"></div> <input type="button" value="Double click the event" ondblclick="demo6()"> </body> </html>
3, BOM object
(1) Introduction to BOM
1. Bom(browser object model): browser object model. When the browser page is initialized, a global object will be created in memory to describe the properties and status of the current window. This global object is called the browser object model.
2. Bom has a core object window, which contains six core modules
1. Document object: document object
2. Frames object: self frame of html
3. History object: the browsing record of the page
4. Location object: the address of the current page
5. Navigator object: contains browser related information
6. Screen object: displays screen related information
(2) Window
① Introduction
1. All browsers support window objects. It represents the browser window, which can be omitted when calling the function. All JavaScript global objects, functions, and variables automatically become members of window objects.
2. Global variables are properties of window objects.
3. The method of window object when global function.
4. For example, the document of html dom is also one of the attributes of the window object.
Window.document.getElementById(),window can be omitted
② Create
Use window objects directly
③ Method
1. Pop up method
1. alert(); Displays a warning box with a message and a confirmation button demonstration
2. confirm(); Displays a dialog box with a message and confirm and Cancel buttons demonstration
3. prompt(); Displays a demonstration of a dialog box that prompts the user for input
2 opening and closing method
(1) open("path to open window"); open a new browser window or find a named window
(2) close(); closes the browser window
3. Timer method
There are two kinds of timer functions in JS:
1. Cycle timer: call a function or code string according to the specified cycle and execute it multiple times.
var timeid=Window.setInterval(code,millisec);
window.clearInterval(timeid); clear the timer to stop the timer from executing functions or code strings.
Parameter Description:
Code: the function to call or the code string to execute.
millisec: the time between periodic code executions or calls
Interval, in milliseconds.
2, timeout timer: after calling the function or code string after the specified milliseconds, it will execute only once.
var timeid=Window.setTimeout(code,millisec);
window.clearTimeout(timeid); clear timer,
It can prevent the execution of the timer.
Parameter Description:
Code: the function to call or the code string to execute.
(6) Location
1. The window.location object can be used to get the current page address (URL) and redirect the browser to a new page
2. The window.location object can be written without the prefix window.
3. Create: window.location/location
4. Method: reload(): refresh the current page
5. Property href: get the requested URL / jump to the specified URL address
6. Case: 3 second jump page
Code example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>3 Second jump page</title> </head> <body> <span id="s1" style="font-size:40px;">3</span> </body> </html> <script> var c; //Page load completion event window.onload = function() { //Cycle timer c = window.setInterval(forward,1000); } var i = 3; function forward() { i--; document.getElementById("s1").innerText = i; if(i == 0) { //Jump to Baidu window.location.href="http://www.baidu.com"; //Clear timer window.clearInterval(c); } } </script>