Javascript
introduce
history
In 1990, browsers appeared
In 1995, the Netscape company Brandon Archie created a scripting language Mocha in 10 days
September LiveScript
November java free ride javaScript
ie: Jscript
1997 European Computer Manufacturers Association ECMA
The first criterion generated: ECMAScript
js and ECMAScript
javaScript is a representation of ECMAScript
ECMAScript is the Syntax Standard for javascript
js concept
js: is an object-based and event driven explanatory scripting language
js features
-
Object based: everything is an object. js can use the object created by itself
-
Event driven: if the effect of the page is driven by events, the browser will respond according to the user's actions
-
Interpretability: compared with the background compilation, the browser can directly recognize and execute the code without interpreting the code
-
Cross platform: js can be executed as long as there is a browser
What can js do
-
Form submission verification
-
cloud computing
-
Dynamic effect
-
Data request
-
...
js version introduction
ECMAScript es5
es6...es10
js component
-
ECMAScript Syntax Standard
-
BOM: Browser Object Models
-
DOM: Document Object Model
Introduction of js
classification
- Hanlin Academician
- Embedded
- Outer chain
Hanlin Academician
Inline event driven: ο nclick = "code"
<div class="a" style="width: 300px;" onclick="alert('This is a box 1')">This is a div</div>
Embedded
Embedded script double tags can be placed anywhere on the page. Suggestions: before the end tag of the body
<script> // Embedded js alert('3'); </script>
Outer chain
The external chain first has a js file suffix: js file directly write js code, introduce js file script, and set double label src as the address of the file
Note: in the script of the outer chain, other embedded code cannot be written, because the embedded code will not be executed
<script src="index.js"> alert('8'); </script>
Usage
-
Use less in the industry
-
Embedded: use more and develop less in the learning process
-
Common for external chain development
Debug statement
-
Debug statement: Syntax: alert('content ') blocks the page
alert('5');
-
console.log('content to output ')
console. Log (value, value 1,...)
box.onmousemove = function(){ // alert('9'); console.log('9'); }
Event Trilogy
- Find, find who to add and get elements for
a. obtain document by ID getElementById(‘id’)
document - document
Get - get
Element – element
ById: pass id
- Add event
Element Event = function() {}
- Specific operation
Element Event = function(){
/ / code operation
}
document.getElementById('box').onclick = function(){ alert('1'); }
report errors
When there is no effect:
-
Check: console
-
See if there are any errors reported
Uncaught TypeError: Cannot set property 'onclick' of null. Cannot add onclick event to null
alert(document.getElementById('box')); // null document.getElementById('box').onclick = function(){ alert('1'); }
window.onload
Wait for the page and resources to load before executing the code
window.onload = function(){
/ / all page operations
}
window.onload = function () { alert(document.getElementById('box')); // Null --- > added window After onload, you can get the element document.getElementById('box').onclick = function () { alert('1'); } }
Mouse event
onclick: Click
Ondbllick: double click
onmouseover: slide in
Onmousenter: slide in
onmouseout: slide out
Onmouselive: slide out
onmousedown: Press
onmouseup: lift
onmousemove: move
oncontextmenu: right click menu
// Click / / document getElementById('box'). Onclick = function() {/ / Alert ('1 '); / /} / / double click debug, double-click comment, and delete the clicked code. Two quick clicks are one double click / / document getElementById('box'). Ondbllick = function() {/ / Alert ('2 '); / /} / / / / slide in: onmouseover onmouseenter when outside the element / / document getElementById('box'). onmouseover = function(){// alert('3');// }// document. getElementById('box'). Onmouseenter = function() {/ / Alert ('4 '); / /} / / / / slide out: onmouseout onmousesave when entering from inside to outside / / document getElementById('box'). onmouseout = function(){// alert('5');// }// document. getElementById('box'). Onmousesave = function() {/ / Alert ('6 '); / /} / / press: press the mouse over the element / / document getElementById('box'). Onmousedown = function() {/ / Alert ('7 '); / /} / / lift: lift the mouse over the element / / document getElementById('box'). Onmouseup = function() {/ / Alert ('8 '); / /} / / move: when the mouse moves over an element, document getElementById('box'). onmousemove = function(){ // alert('9'); console.log('9');}// Right click menu: when right clicking document getElementById('box'). oncontextmenu = function(){ alert('10');}
The difference between over and enter
onmouseover and onmouseout are a group of corresponding slide in and slide out. When over enters a child element from a parent element, the event of the parent element will also be triggered, and the event of the parent element will not be triggered by enter
// Event trilogy / / document getElementById('box'). onmouseover = function () {// console.log(1);// }// document. getElementById('box1'). onmouseenter = function () {// console.log(2);// }document. getElementById('box'). onmouseout = function () { console.log(1);} document. getElementById('box1'). onmouseleave = function () { console.log(2);}
variable
Variable declaration
Variable: the container used to store all data
Declare variables with var
Syntax: var variable name = value;
When used to store data
// 1. First declare, then assign, set X; x = 10; var a; a = 20; console. log(a);// 2. Declare and assign var b = 'abc'// All letters except variables are quoted console log(b);// 3. Declare multiple, declare first and then assign var c, d, e// Declaration c = 50;d = e = 'cdf';// console.log(c);// console.log(d);// console.log(e);console.log(c, d, e);// 4. Multiple simultaneous declaration of var m = 20, n = 30;console.log(m, n);var o = p = 'abc';console.log(o, p);
Naming conventions
Mandatory:
-
Composed of letters, numbers$ Composition, number cannot start
-
Keywords and reserved words cannot be used
-
It cannot be repeated. If repeated, the following one will overwrite the previous one
Recommendations:
-
Semantic userName password
2. Follow the small hump naming method. Multiple words form a naming system, Capitalize the first letter from the second word userName userPassword userAgeAndName
// var 1a = 30; Error reporting var $a = 30// var var = 20; Error / / var class = 40; Error reporting var $a = 50;console.log($a);
The form is worth operating
obtain
-
Syntax: form elements value
-
Note: if there is a value attribute on the option, the content in the value is obtained. If there is no value, the content in the middle of the option is obtained
// Get the value of input. First get the input element var InP = document getElementById('inp');// Debug console log(inp); // Null indicates failed to get console log(inp.value); // 123456 / / get the text field var text = document getElementById('text'); console. log(text); console. log(text.value);// Get the drop-down list var city = document getElementById('city'); console. log(city); console. log(city.value);
set up
-
Syntax: form elements value = content to be set;
-
Note: if there is a value attribute on the option, the content in value is set. If there is no value, the content in the middle of the option is set
// Set the value of inp to Xiao Qiao inp Value = 'Little Joe'; text.value = 'glory of the king'// city.value = 'bj';city.value = 'bj '; // Can't choose Beijing
Close the contents of the label
obtain
Double label closed label
Operation content: the content between the start tag and the end tag is called the content
obtain:
innerHTML: var variable = tag innerHTML;
\1. That can identify the label
innerText: var variable = label innerText;
\1. Unrecognizable label
var box = document.getElementById('box');console.log(box);var html = box.innerHTML;console.log(html);var text = box.innerText;console.log(text);
set up
label. innerHTML = 'content to be set';
label. innerText = 'content to be set';
-
The content of the original label will be overwritten when setting
-
The back will cover the front
-
When setting, innerHTML can set the tag, innerText cannot set the tag
box.innerHTML = 'This is what I passed js Set content';box.innerHTML = 'This is a new div';box.innerText = 'This is a text content';box.innerText = '<i>This is a text content</i>';box.innerHTML = '<i>This is a text content</i>';
Operation properties
On the start tag, all attributes except the start tag name are tag attributes
On the start tag, the attribute name is on the left of the equal sign [=], and the attribute value is on the right
Get: var variable = element Attribute name; var variable name = element ['attribute name']; var variable 1 = element [variable 2];
Settings: elements Attribute name = 'value'; Element ['attribute name'] = 'value'; Element [variable] = 'value';
// Get the element var box = document getElementById('box'); console. log(box); console. log(box.id); // boxbox. id = 'b'; var idName = box['id']; console. log(idName); var aa = 'id'; // Variable console log(box[aa]); box[aa] = 'bBox';
Operation id
Get: var variable = element id;
Settings: elements id = 'value';
var box = document.getElementById('box');console.log(box);console.log(box.id); // boxbox.id = 'b';
Operation src
Get: element src obtains the absolute path, and generally does not use the relative path
Settings: elements src = 'address'; Address: relative path relative to the current html path/ Peer... / jump one level up
var img = document.getElementById('img');console.log(img);console.log(img.src); // file:///E:/1026/day01/img/1.jpg Absolute path img src = './ img/2. jpg';
Operation class
Get: var variable = element className;
Settings: elements className = 'value';
When to use className
-
When setting styles in batch
-
When the style changes with the mouse, click div to change the style of Div
aBox.className = 'aa';aBox.onclick = function(){ aBox.className = 'cc';}
div{ width: 200px; height: 200px; background: red;}.aa{ width: 500px; height: 500px; background: pink; border: 10px solid skyblue;}.cc{ width: 200px; height: 300px; background: #f09811; padding: 30px;}
Operation style
You can only manipulate inline styles
Single operation
Get: element style. Attribute name (width height padding)
Settings: elements style. Attribute name = 'value';
Styles can be accumulated and only one style can be changed
var box = document.getElementById('box');console.log(box);console.log(box.style.width);console.log(box.style.height);box.style.width = '1000px';box.style.height = '1000px';box.style.color = 'white';
Note: - "is not allowed in js to convert words with hyphens into hump nomenclature
font-size: fontSize
// box.style.font-size = '100px'; // Error box style. fontSize = '100px';
Batch operation
Batch style setting: all the values on the style in the row are obtained
Get: element style.cssText
Settings: elements style.cssText = 'value';
Value: consistent with the writing method in css style sheet;
cssText will overwrite all the values of style on the original label
Set initial style regression initial style
console.log(box.style.cssText); // width: 1000px; height: 1000px; color: white; font-size: 100px;box.style.cssText = 'color: #f00; background: purple;width:1000px;height: 1000px;';
data type
classification
- Basic data type
- Number: number
- string: string
- boolean: boolean value
- Null: null
- undefined: empty
- Complex / reference / composite data types
- Object: everything is an object
- Array: array
- Function: function
Inspection data type
typeof data
Typeof (data)
Basic data type
value type
-
Integer: integer
-
Floating point type: a value with one decimal point and no 0 after the decimal point
Note: the decimal calculation is not accurate due to the accuracy of the computer
-
Special value:
-
NaN: Not a Number is not a number
It will appear when the calculation is wrong
characteristic:
- NaN uses the typeof test to test the result number
- NaN and any numerical results are NaN
- NaN is not equal to any value, including itself
-
Hexadecimal number
- Octal: starts with 0 and is not followed by a number greater than 8
- Hex: starts with 0x, 0-9a-f stands for 0-15 a – 10 b – 11
-
Infinity -Infinity divisor is 0
-
e – power of 10
var a = 30;console.log(a);console.log(typeof a); // numberconsole.log(typeof(a)); // numbervar b = 22.01;console.log(typeof b);console.log(0.1 + 0.2); // Due to the problem of computer accuracy, the decimal calculation is inaccurate 0.3000000000000004console log(1/3); console. log(10 - 'a'); // NaNconsole. log(typeof NaN); // numberconsole. log(NaN + 10); console. log(NaN - 10); console. log(1 == 1); // Set up console log(NaN == NaN); // falseconsole. log(NaN == 10); var c = 070; console. log(c); var d = 019; console. log(d); var m = 0xa; console. log(m); var n = Infinity; var n = -1/0; console. log(n); console. log(typeof n); var mn = 2e20; // 10 times of 2 * 10 console log(mn);
-
string
String: string, wrapped in pairs of single and double quotation marks is the string ''
Length: string Length gets the length of the current string
charAt: string charAt (subscript)
String [subscript]: it can only be used if it is consistent ie8 with charAt
Subscript: the serial number starts from the first character, starts from the starting character, starts from left to right, and starts from 0
var str = "abc";console.log(str);console.log(typeof str); // stringvar str1 = '30'; console. log(str1); console. log(typeof str1); // Stringvar STR2 = "from 0:00 to 24:00 on November 23, 31 provinces (autonomous regions and municipalities directly under the central government) and Xinjiang production and Construction Corps reported 22 new confirmed cases, including 20 imported cases (4 in Fujian, 4 in Guangdong, 3 in Shanghai, 3 in Sichuan, 2 in Jiangsu, 2 in Shaanxi, 1 in Inner Mongolia and 1 in Henan), and 2 local cases (1 in Tianjin and 1 in Shanghai) ; No new deaths; One new suspected case was imported from abroad (in Shanghai). On the same day, 15 cured discharge cases were added, 189 close contacts were released from medical observation, and the severe cases were the same as the previous day. There are 303 confirmed cases imported from abroad (including 2 severe cases) and 1 suspected case. There were 3804 confirmed cases, 3501 cured cases and no deaths. As of 24:00 on November 23, according to the reports of 31 provinces (autonomous regions and municipalities directly under the central government) and Xinjiang production and Construction Corps, there are 322 confirmed cases (including 6 severe cases), 81508 cured and discharged cases, 4634 dead cases, 86464 confirmed cases and 1 suspected case. A total of 877545 close contacts were tracked, and 11857 close contacts were still under medical observation. 31 provinces (autonomous regions and municipalities directly under the central government) and Xinjiang production and Construction Corps reported 8 new asymptomatic infections (all imported from abroad); 6 cases were confirmed on the same day (5 cases were imported from abroad); On the same day, 11 cases of medical observation were cancelled (all imported from abroad); 348 cases of asymptomatic infection are still under medical observation (345 cases imported from abroad). "; console.log(str2.length); / / to find the 52nd word, serial number: 51. The first word: serial number 0console.log(str2.charAt(51));console.log(str2.charAt(0));console.log(str2[51]);
boolean
boolean: boolean value true – true false – false
Usage:
-
Result of comparison operator
-
Judgment condition or result of judgment condition
var t = true;console.log(t);console.log(typeof t); // booleanvar f = false;console.log(f);console.log(typeof f); // booleanconsole.log(1 == 1); // trueconsole.log(1 == 2); // false
null
null: a real empty object has only one value of its own
When the data is occupied, there is no data now, but there will be data in the future
Return result after typeof verification: object
var n = null;console.log(null);console.log(typeof null); // object
undefined
undefined: when only variables are declared but not assigned, there is only one value of itself
It's worth the vacancy
var a;console.log(a);console.log(typeof a); // undefined
Note: js specifies that null and undefined are equal (= =)
console.log(null == undefined); // true
Complex data type
object
-
Object: object, everything is an object
-
Create object: var variable name = {};
-
In json format: {'attribute name': attribute value, 'attribute name 1': attribute value 1,...}
-
Value: object name Property name object name ['property name'] object name [variable]
var box = document.getElementById('box');console.log(box);console.log(typeof box);console.log(typeof document);console.log(typeof window);var obj = { 'name': 'Peng Yuyan', 'age': 33, 'height': 185};console.log(obj);console.log(typeof obj);console.log(obj.name);console.log(obj['name']);var nn = 'age';console.log(obj[nn]);console.log(obj.nn); // undefined
array
-
A container used to store indefinite amounts and types of data
-
Declaration: var variable name = [value, value 1,..., value n];
Index: subscript number starting from 0
Elements: Values
- Gets the element of the specified subscript: array [subscript]
var arr = [];console.log(arr);var arr1 = [20, NaN, 'abc', null, undefined, true, false, obj, box, window];console.log(arr1);console.log(arr1[4]);console.log(arr1[7]);
function
Function: the function saves a piece of code and is called when necessary
-
Declaration: function function name () {/ / code block}
-
Call: function name ();
Note: only declaration, function has no effect
function fun1(){ console.log(1);}fun1();fun1();fun1();fun1();fun1();fun1();fun1();
Data storage location
The basic data type is stored in the stack. The data is relatively single and the data capacity is relatively small
Complex data types are stored in the heap, with diversified data types and relatively large data capacity
/* typeof: Return itself: number string Boolean undefined function return object: null object array the basic data type is stored in the stack, the data is relatively single, the data capacity is relatively small, the complex data types are stored in the heap, the data types are relatively diverse, and the data capacity is relatively large*/console.log(typeof null);console.log(typeof []);function a(){ console.log(1);}console.log(typeof a);
Force conversion
Number
Number (data to be converted)
Null character, space character, pure numeric string, boolean, null
NaN is returned when conversion fails
console.log(Number('')); // 0console.log(Number(' ')); // 0console.log(Number('a')); // NaNconsole.log(Number('123')); // 123console.log(Number('20px')); // NaNconsole.log(Number(true)); // 1console.log(Number(false)); // 0console.log(Number(null)); // 0console.log(Number(undefined)); // NaN
parseInt
Hexadecimal number: not required
ParseInt (data to be converted, hexadecimal number);
Convert each character from left to right. If it cannot be converted, it will stop. If the first letter cannot be converted, it will return to NaN
Return integer
console.log(parseInt('33.3px'));console.log(parseInt(''));console.log(parseInt('070', 8));console.log(parseInt(true));
parseFloat
Parsefloat (data to be converted);
When converting each character from left to right, it will stop if it cannot be converted. If the first letter cannot be converted, it will return to NaN
Return integer, floating point
console.log(parseFloat('33.3px'));console.log(parseFloat('33.3.333px'));
isNaN
Judge whether a data is a number
IsNaN (data to be converted)
The Number method is automatically called for conversion
If the conversion is successful (number), false is returned
Conversion failed (NaN), return true
console.log(isNaN('123')); // falseconsole.log(isNaN('123a')); // trueconsole.log(isNaN('true')); // 'true '--- string number Nan trueconsole log(isNaN(true)); // false console. log(isNaN(undefined)); // true
toString
Data ToString (base);
Hexadecimal: it is not necessary to pass. It only has an effect on numbers
var num = 10;console.log(num.toString());console.log(typeof num.toString());var num1 = 70;console.log(num1.toString(2));var num2 = NaN;console.log(num2.toString());console.log(typeof num2.toString()); // stringvar t = true;console.log(t.toString()); // true// . Equivalent to toString of T and toString of N / / var n = null// console. log(n.toString()); // Error reporting var u = undefined// console. log(u.toString()); // Error var obj = {}; console. log(obj.toString()); // [object] all objects will be converted to this result var arr = [1,2,4];console.log(arr.toString()); // "1,2,4"
String
Force conversion
String (data to be transferred)
console.log(String(null));console.log(String(undefined));console.log(String({}));console.log(String([1, 3,2,3]));
Boolean
boolean: true true false false
Syntax: Boolean (data to be converted); true/false
True or false in js:
False: 0 NaN null character false null undefined
True: it's true except false
console.log(Number(true)); // 1console.log(Boolean(1)); // trueconsole.log(Boolean(-1)); // trueconsole.log(Boolean(0)); // falseconsole.log(Boolean(NaN)); // falseconsole.log(Boolean('')); // falseconsole.log(Boolean(' ')); // trueconsole.log(Boolean(null)); // falseconsole.log(Boolean(undefined)); // falseconsole.log({});console.log(Boolean({}));
operator
-
Arithmetic operators: + - * /% + –
-
Assignment operator: = + = - = * = / =%=
-
Comparison operator: > > = < < = = (equal) = (congruent)= (wait)! (incomplete)
-
Logical operators: & & (and) | (or)! (negative if not)
-
Ternary operator: condition? Code executed when the condition is true: code executed when the condition is not true
// Arithmetic console log(10 + 20); // 30console. log(10 % 3); // 1console. log(10 % 5); // 0 / / + + self addition, based on itself + 1, can be written in front of the variable or after the variable var a = 30;a++;console.log(a); // 31++a;console.log(a); // 32 / / when + + and other codes are on the same line, add + + first and execute other codes first++ After, execute other code first, and add var b = 10;console.log(++b); // ++b; console.log(b); 11console.log(b); // 11var c = 10;console.log(c++); // console.log(c); 10 c++;console.log(c); // 11 / / -- when it is on the same line with other codes, -- before, subtract from it to execute other codes-- After that, execute other code first, and after self subtraction, var d = 33;console.log(--d); // --d; console.log(d); 32var e = 22;console.log(e--); // console.log(e); 22 e--;console.log(e); // 21 / / assign a value to a variable, VAR B = 30; console. log(b);// Every time you add 10, you change var s = 10 based on the current value; s += 10; // s = s + 10console. log(s);// %= var mn = 100; mn %= 33; // mn = mn % 33; console. log(mn); // 1 / / comparison operator: > = < < = = (equal) = = = (congruent)= (wait)== (incomplete) / / the result of the comparison operator is only: true false second log(1 > 2); // falseconsole. log(1 < 2); // trueconsole. log(2 >= 2); // True / / = = equal: compare only values / / = = equal: compare both values and data types console log(1 == 1); // trueconsole. log('1' == 1); // trueconsole. log('1' === 1); // The values are all 1 strings, and the values are not equal. False / /! =: Compare values only / /! = =: Compare both numeric and data types console log('1' != 1); // falseconsole. log('1' !== 1); // Values are equal and data types are not equal trueconsole log(3>2>1);// Logical operators: & & (and) | (or)! (non negation) / / & &: there is a condition on both sides. If the conditions on both sides are true, it returns true. If there is a false, it returns false second log(1 > 2 && 2 < 3); // false && true false// 3 > 2 true > 1console. log(3>2>1);// ||: Each side has a condition. If both conditions are false, false will be returned. If there is a true condition, trueconsole will be returned log(1 > 2 || 2 < 3); // false || true true// !: The result is the Boolean console log(!true); // Not true false second sole log(!''); // ! False true / / ternary operator: condition? Code executed when the condition is true: code executed when the condition is not true. / / simple judgment. / / Note: semicolons are not allowed in the ternary operator. / / if 1 > 2, 1 pops up, otherwise 21 > 2 pops up? alert(1) : alert(2);// 1 > 2 ? alert(1); : alert(2); report errors
Implicit conversion
Implicit conversion:
+ - * /% + + - occurring in arithmetic operators
Rules:
-
The calculation between values is normal
-
There is string addition, which is spliced after being converted into a string
-
In addition and other operations without strings, it is possible to convert them into numbers before calculating (Number)
-
If there is an array or object, first call its own toString method, convert it into a string, and then calculate according to the above rules
console.log(10 + 20); // 30console.log(10 - 20); // -10console.log(0 * 1); // 0console.log('' + 123); // '123'console.log('a' + NaN); // aNaN console.log('1' + true); // 1trueconsole.log('1' + null); // 1nullconsole.log('1' + undefined); // 1undefinedconsole.log('a' - '1'); // NaN - 1 NaNconsole.log(true * 10); // 1 * 10 10console.log(null / 30); // 0 / 30 0console.log(true + false); // 1 + 0 1console.log(true + {}); // true + '[object Object]' true[object Object]console.log(true - {}); // true - '[object Object]' 1 - NaN NaNconsole.log(false + []); // false + '' falseconsole.log(false - []); // false - '' 0 - 0 0console.log(null * [2]); // null * '2' 0 * 2 0console.log(null * [2,3]); // null * '2,3' 0 * NaN NaN
Process control statement
A statement that executes code according to a specified process
classification
-
Sequential statement: the order of execution from top to bottom
-
Conditional / branch statement: if else switch
-
Loop statement: a statement that causes code to execute a fixed number of times
for while do while
- Other statements: break continue
Conditional statement
if
Syntax:
If (conditional){
/ / code executed when the condition is true
}
Abbreviation: if (condition) code executed when the condition is true
Only the first code after the condition can be controlled
var today = 'Wednesday';if(today == 'Friday'){ // 'Wednesday' = = 'Friday' false / / 'Friday' = = 'Friday' true alert ('rest tomorrow ');} if(true){ alert(1);}// Abbreviated mode var money = 10; If (money = = 100) {alert ('eat snacks'); alert ('eat hot pot ');} if(money == 100) alert('eat snacks'); Alert ('eat hot pot ');
if else
Syntax:
If (conditional){
/ / code executed when the condition is true
} else {
/ / code executed when the condition is false
}
// 100 hot pot snacks, otherwise bread var money = 10; If (money = = 100) {alert('eat hot pot '); alert('eat snacks');} Else {alert('eat bread ');}
if else nesting
Syntax:
If (conditional){
/ / code executed when the condition is true
} else if (condition 1){
/ / code executed when condition 1 is true
} else {
/ / code executed when none of the above conditions are met
}
// EVAR core = 58 at 90 a 80 B 70 C 60 d 60; if (core >= 90) { console.log('A');} else if (core >= 80) { console.log('B');} else if (core >= 70) { console.log('C');} else if (core >= 60) { console.log('D');} else { console.log('E');}
switch
Syntax:
Switch (condition / variable){
case result 1:
Code executed when result 1 is met;
break;
case result 2:
Code executed when result 2 is met;
break;
case result 3:
Code executed when result 4 is met;
break;
default:
The code executed when the above results are inconsistent;
break;
}
switch: it is more applicable when the conditions and results are relatively single
break: prevent penetration
If you do not add break, when the switch matches a matching result, the following results do not match. Directly execute all the following codes
var c = '-';switch (c) { case '+': console.log(20 + 30); break; case '-': console.log(20 - 30); break; case '*': console.log(20 * 30); break; case '/': console.log(20 / 30); break; default: alert('Current operator error'); break;}
Circular statement
-
Get document. By ID getElementById(‘id’)
-
Get by tag name:
document / parent element getElementsByTagName('tag name ');
Tag get element
document / parent element getElementsByTagName('tag name ');
- What is obtained through the tag name is a collection, class array, with length and subscript
Length: length
Subscript: a number starting from 0 from left to right
- Elements with specified subscript: set [subscript]
Note: even if only one element is obtained, it is stored in the collection
var lis = document.getElementsByTagName('li');console.log(lis); // Htmlcollection (10) collection of HTML collection elements [Li, Li, Li, Li, Li, Li, Li, Li, Li, Li] console log(lis.length); console. log(lis[4]); var uls = document. getElementsByTagName('ul'); console. log(uls[0]); // Htmlcollection collection / / if there is only one parent element, directly obtain the element with the specified subscript var UL = document getElementsByTagName('ul')[0]; console. log(ul); // Just want to get livar LIS1 = ULS [0] in the first UL getElementsByTagName('li'); console. log(lis1);
Get element by class name
document / parent element getElementsByClassName('class name ');
- What is obtained through the tag name is a collection, class array, with length and subscript
Length: length
Subscript: a number starting from 0 from left to right
- Elements with specified subscript: set [subscript]
Note: even if only one element is obtained, it is stored in the collection
// Through the element of box, VAR boxes = document getElementsByClassName('box'); console. log(boxes);// Boxconsole in the second ul log(uls[1]); var box1 = uls[1]. getElementsByClassName('box'); console. log(box1); // [li.box]
Differences in various ways of obtaining elements
-
id:
Get the element directly and operate it directly. The element can only be obtained through document
Static (get it first, add the element, and you can't get it)
-
tagName/className:
What is obtained is that the collection can be operated only after the element is obtained through subscript, which can be either document or parent element
Dynamic (you can get it first and then add elements)
// var eight = document.getElementById('eight');// console.log(eight);// var boxes = document.getElementsByClassName('box');// console.log(boxes); // [li.box]// eight.style.background = 'red';// boxes[0].style.background = 'red';var ul = document.getElementsByTagName('ul')[0];console.log(ul);var ten = document.getElementById('ten');// Add a liul with ID ten to the UL innerHTML = ul. InnerHTML + '< Li id = "ten" > this is the tenth ID < / Li >'; console. log(ten); // nullvar box1 = document. getElementsByClassName('box1'); ul. innerHTML = ul. InnerHTML + '< Li class = "box1" > this is class < / Li >'; console. log(box1); // [li.box1]
loop
for
grammar
for: lets the loop body execute the specified number of times
For (expression 1; expression 2; expression 3){
Circulatory body
}
For (initialization variable; loop condition; variable update){
Circulatory body
}
explain
Initialization variable: var variable name = value;
Loop condition: if that condition is met, the loop will execute
Variable update: + + –
for(var i = 1; i <= 100; i++){ console.log(i);}
Perform steps
-
Initialization variable: var i = 1;
-
Cycle condition: I < = 5;
-
Loop body: console log(i);
-
Variable update: i + +;
2342342
for(var i = 1; i <= 5; i++){ console.log(i);}// Error demonstration / / for (VaR I = 1; I > = 1; I + +) {/ / console.log (I); / /}
be careful
- Execution time: the for loop is executed at the moment when the page is loaded
- Note: there must be available conditions for the end of the cycle. If there is no end, an dead cycle will be formed
breakpoint debugging
Right click the browser - check - source - file - double click - click in front of the specific line - refresh - small dot blue - refresh
Variation of for
-
grammar
Initialize variables;
for(; loop condition;) {
Circulatory body;
}
Note: two semicolons cannot be omitted
// 1-5 starting value 1var I = 1; for(;i<=5;) { console.log(i); i++;}
for in
The for loop can traverse numbers, collections, but not objects
for in for traversing objects
Syntax:
for(var variable name in data){
Circulatory body
}
Attribute name: variable name
Attribute value: data [variable name]
var obj = { 'name': 'Peng Yuyan', 'height': 180, 'age': 33};for(var k in obj){ console.log(k, obj[k]);}
while
while syntax:
Initialize variables;
While (loop condition){
Circulatory body;
Variable update;
}
// 1-5 while// var i = 1;// while(i<=5){// console.log(i);// i++;// }
dowhile
Initialize variables;
do{
Circulatory body;
Variable update;
}While (cycle condition);
// do while// var j = 1;// do{// console.log(j);// j++;// }while(j<=5);
difference
The first cycle condition is not met: while will not be executed once, while dowile will be executed once
var i = 6;while(i<=5){ console.log(i); i++;}var j = 6;do{ console.log(j); j++;}while(j<=5);
break and continue
break: prevent penetration; Terminate the cycle;
Continue: abort the current cycle and continue the next cycle
for(var i = 0; i < 5; i++){ // If I equals 2, terminate / abort the loop if (I = = 2) {/ / break; / / neither the following code nor the loop will go through 0 1 continue; / / abort the current cycle. The following code will not go through 0 1 3 4} console log(i);}
this
The concept of this
This: this pronoun stands for whoever uses it
this exists inside or outside the function
this exists anywhere on the page
Page understanding
html – > document is the parent element of the whole page
Ancestor - > window entire browser window object
Global scope under script tag
The declared variables and functions belong to a property and method of window
Variable - attribute
Function method
If the variables and attributes are directly hung on the window, the window will be omitted
var a = 20;console.log(window);console.log(window.a);console.log(a);function am(){ console.log(1);}console.log(window.am);window.am();
The direction of this
-
Global this: window
console.log(this); // window
-
Ordinary function this: window
function am(){ console.log(1); console.log(this, '1----'); // Who uses the window is who}console log(window.am); window. am();
-
Click who this points to in the event - > the trigger source point of the event is who
var lis = document.getElementsByTagName('li');console.log(lis); // [li, li, li, li, li]console.log(lis[0]);// Add click event LIS [0] onclick = function(){ // alert(1); console.log(this);}
-
Object method: this points to the object itself
// Object, VAR obj = {'name': 'Peng Yuyan', 'Tip': function() {console. Log (this);}}; console. log(obj); console. log(obj.tip); // Object Property name obj tip(); // Object method: this points to the object itself
Application of this
-
When you can't get the correct subscript in the event, you can't get the element this
/* Click each li to make the background color of the li turn red*/// 1. Get the element var LIS = document getElementsByTagName('li'); console. log(lis);// Each for (VaR I = 0; I < LIS. Length; I + +) {console.log (LIS [i]); / / get Li / / add the event lis[i].onclick = function() {/ / make the background color of this Li turn red console.log (I); / / the 9 for loop is executed at the moment of page loading, and I becomes the end condition 9 console.log (LIS [i]) ; // Undefined / / when the correct subscript is not obtained in the event and the element is not obtained, this console log(this); this. style. background = 'red'; }}
-
Use this as the parent element to get the child element
/* Slide in each li to display the p tag in the li*/// 1. Get the element var LIS = document getElementsByTagName('li'); console. log(lis);// For (VaR I = 0; I < LIS. Length; I + +) {/ / add the marked event LIS [i]. Onmousenter = function() {console.log (LIS [i]); / / the corresponding Li console.log (this); / / obtain the child element var P = this.getelementsbytagname ('p ') [0]; console.log (P); p.style.display =' block ';}// Slide down the event LIS [i] Onmousesave = function() {console.log (LIS [i]); / / corresponding Li console.log (this); / / obtain the child element var P = this. GetElementsByTagName ('p ') [0]; console.log (P); p.style.display =' none ';}}
Custom properties
- Attribute: all attributes written on the start tag except the start tag name are attributes
id src class style intrinsic attribute
Custom attributes with their own specified names and attribute values
-
Custom attribute operation is consistent with intrinsic attribute operation: get: element Attribute name element ['attribute name'] setting: element Attribute name = value
-
The custom attributes written on the label cannot be obtained directly by the methods in points and []
-
The custom attribute set by js can't be seen on the tag, but it can be obtained and set normally
var div = document.getElementsByTagName('div')[0];console.log(div);console.log(div.tx); // undefinedconsole.log(div['tx']); // undefineddiv.ex = 1;console.log(div.ex); // 1
Application of custom attributes
- Add a switch to each element in the for loop and add it with custom attributes
- Judge your own switch custom attribute in the click event
/* Click each div, if the current height is 100px, it becomes 300, if the height is 300px, it becomes 100px*/// 1. Get the element var divs = document getElementsByTagName('div'); console. log(divs);// If you don't know what the current state is, assume that the state var tag = 1// 1 --- 100 2 --- 300 / / use one switch to control multiple divs / / each for (VaR I = 0; I < divs. Length; I + +) {console.log (divs [i]); / / get each div / / add a switch to each element, and the custom attribute divs [I]. Tag1 = 1; / / 1 --- 100 2 --- 300 / / add the event divs[i].onclick = function() {/ / output tag console.log (this, this.tag1); // // Judge your own switch custom attribute if (this. Tag1 = = 1) {this. Style. Height = '300px'; this. Tag1 = 2;} else { this.style.height = '100px'; this.tag1 = 1; } }}
Custom index
If there are several buttons, there are several data relationships: buttons and data subscripts correspond one-to-one
Custom index:
Stores the value of a custom attribute as a subscript custom index
1. Elements in the for loop Attribute name = i;
2. Get custom index: In the event: this.index You can get the custom index
Example 1
var arr = [ "HTML", "CSS", "javascript"];var btns = document.getElementsByTagName('button');console.log(btns); // [button, button, button] / / add a click event for (VaR, I = 0; I < BTNs. Length; I + +) {console.log(i); / / during the for loop, I can the correct value. / / store the value of the custom attribute as a subscript custom index BTNs [i]. Index = I; BTNs [i]. Onclick = function() {/ / you can only get the corresponding data in the array through subscript / / console.log(i); / / get the custom index and custom attribute console.log(this.index); / / get console.log (arr [this. Index]); alert (arr [this. Index]) from the array;}}
Example 2
When the last operation cannot be known, use exclusive thinking to achieve the effect
Clear all styles first, and then add styles to the specified button
/* Click each button to switch the background color of the body and remove the color from the array. The background color of this button becomes black. The relationship between other unchanged buttons and data: subscripts correspond one by one*/var arr = ['yellow', 'red', 'pink'];// 1. Get the element var BTNs = document getElementsByTagName('button'); console. log(btns); // [button, button, button] / / click each button for (VaR I = 0; I < BTNs. Length; I + +) {/ / get each button console.log(btns[i]); / / store the custom index btns[i].index = i; / / click the event btns[i].onclick = function() {/ / obtain the data in the corresponding array through the subscript. / / obtain the subscript of the button. / / console.log(i); / / the user-defined index cannot be used correctly. / / obtain the user-defined index console.log(this.index); / / obtain the data of the corresponding subscript console.log(arr[this.index]); document.body.style.background = arr[this.index]; // If you can't know the last operation. / / clear all the styles first, and then add a style to the specified button. / / exclusive. / / 1 Clear all styles for (VaR J = 0; J < BTNs. Length; j + +) {BTNs [J]. Style. Background = '';}// 2. The background color of this button turns black this style. background = 'green'; }}
Example 3
/* Tab effect 1 Layout 2 js*//* Click each button to switch the content to the corresponding button. The background color of the button changes and the font also changes*/// 1. Get the content of the element button. / / if there is a parent element, use the parent element to get var box = document getElementById('box'); console. log(box); var btns = box. getElementsByTagName('button'); var divs = box. getElementsByTagName('div'); console. log(btns, divs);// 2. Add the click event for (VaR I = 0; I < BTNs. Length; I + +) {/ / save the index btns[i].index = i; / / add the event btns[i].onclick = function() {/ / switch to the corresponding content and display it through the subscript setting. / / the subscript of the content corresponds to the subscript of the button one by one. / / the subscript of the button is used as a user-defined index. / / the index console.log(this.index); / / only one exclusive operation is displayed. / / 1. Clear all class names for (var j = 0; j < divs.length; j++){ divs[j].className = ''; btns[j].className = ''; } // Display the corresponding content box divs [this. Index] className = 'active'; // The button should also display the corresponding style this className = 'active'; }}
function
Function concept
Function: a block of code that is event driven or executed when it is called
It is used to save a piece of code and is called when necessary
Function declaration method
Function declaration
-
Declare function function name () {/ / code block}
-
Calling function: function name ();
function s(){ console.log(1);}s();
Expression declaration
-
Declare function var variable name = function() {/ / code block}
-
Calling function: variable name ();
var su = function(){ console.log(2);}su();
Usage scenario
-
Purposeful function
function sum(){ // Save sum var s = 0// Sum of each number in 1-100 for (VaR I = 1; I < = 100; I + +) {S + = I;} console. log(s); // 5050}sum();
-
Event handler
document.onclick = function(){ alert(1);}
-
Object method
var obj = { 'name': 'Peng Yuyan', 'tip': function(){ console.log('Earn 100 w'); }};obj.tip();
-
Package reuse
Purpose: make the page code less. Put the same repetitive code in a function and call it
Function encapsulation:
-
Create a new empty function
-
Analyze the duplicate code and paste the duplicate code into the function
-
Call the function at the location of the source code to see if it executes normally
// 1. Get the element right arrow img divvar right = document getElementById('right'); var img = document. getElementById('img'); var sz = document. getElementById('sz'); var dm = document. getElementById('dm'); console. log(right, img, sz, dm);// When the picture name is irregular, var arr = ['./img/11.jpg', './img/22.jpg', './img/33.jpg', './img/44.jpg']// If you don't know which graph it is, suppose you save var n = 0// Array subscript starts from 0 / / 2 Add event, click the right arrow Onclick = function() {/ / switch picture 1 -- > 2 subscript 0 --- 1 move();}/* Left arrow: click the left button head to switch the picture 4 -- 3 -- 2 -- 1 -- 4 * / var left = document getElementById('left'); console. log(left);// 2. Add event left Onclick = function() {/ / N 4 -- 3 -- 2 / / N --; / / minus one -- "minus 2 N - = 2; console.log (n); move(); / / add one} / * purpose: to reduce the page code, put the same repetitive code in a function and encapsulate it in the calling function: 1 Create a new empty function 2 Analyze the duplicate code and paste the duplicate code into the function 3 Call the function at the location of the source code to see if it is executed normally * / function move() {n + +; console.log (n); / / if n is - 1, return to 3 if (n = = - 1) {n = 3;}// When n becomes 4, return to the first if (n = = 4) {n = 0;}// Get the corresponding picture address console log(arr[n]); // Render SRC img of img src = arr[n]; // Update text content elements InnerHTML = when the value count starts from 1, the string will be spliced Sz innerHTML = '' + (n + 1) + '/4'; dm. InnerHTML = 'animation' + (n + 1);}
-
Parameters of function
When to use parameters:
When there is an uncertain term in the function, it is drawn into a parameter
Classification of function parameters:
- Formal parameter: a formal parameter used as a placeholder parameter, similar to a variable, written after function ()
Function: receive data passed from arguments
-
Arguments: actual parameters, actual data, data passed to formal parameters, written in function call ()
-
Arguments: a collection of arguments when it is uncertain how many parameters there are
Single parameter
function sum(a){ // A --- formal parameter console log(a); // 10}sum(10); // 10 --- argument / / calculate 10 + 20 10 + 40 10 + 100 10 + 1000function s (a) {console.log (10 + a); / / uncertain item}s(20);s(40);s(100);
Multiple parameters
Multiple formal parameters accept the data passed by multiple arguments, separated by
function s(a, b){ console.log(b + a); // Uncertain items}s(20, 30);s(40, 33);s(100, 10);s(87, 44);
arguments
Arguments: a collection of arguments, when it is uncertain how many parameters there are
function sum() { // If you are not sure how many parameters there are, simply don't write any / / each function has a set of arguments: arguments console log(arguments); var s = 0; // Add up every data in the set for (VaR I = 0; I < arguments. Length; I + +) {console.log (arguments [i]); s + = arguments [i];} console. log(s);} sum(); sum(33, 45, 67); sum(1, 4, 5, 2, 78);
Type of parameter
Parameter data type: can be all data types
Basic data type: number string boolean null undefined
Generally, null\undefined is not used as an argument
Complex data type: object array function
function typeN(a){ console.log(a, typeof a);}var num = 20;typeN(num); // numbervar str = '1234'; typeN(str); var bool = true; typeN(bool); var n = null; typeN(n); var un = undefined; typeN(un); Var obj = {'name': 'Peng Yuyan'}; typeN(obj);var arr = [1,2,3,4,5];typeN(arr);function a(){ console.log(1);}typeN(a);
Function problem
-
If the function name is repeated, the following function will overwrite the previous one
-
More formal parameters than arguments: assign values to each formal parameter from left to right, and the remaining formal parameters will be undefined
More arguments than formal parameters: assign values to each formal parameter from left to right. Redundant arguments cannot be obtained through formal parameters
/* 1. If the function name is repeated, the following function will overwrite the previous one*/function sum() { console.log(1);}function sum() { console.log(2);}sum(); // 2/* 2. More formal parameters than arguments: assign values to each formal parameter from left to right, and the remaining formal parameters will be undefined. More than formal parameters: assign values to each formal parameter from left to right, and redundant arguments cannot be obtained through formal parameters * / function s (a, B, c) {console.log (a, B, c);} s(10); s(20, 30, 40, 50);
document.write and innerHTML
Can identify the label
document. Write:
Can only operate on body
window. When used in onload, the original content of the page will be overwritten
The content added by itself will not be overwritten
innerHTML:
Manipulate all closed labels
All contents in the original label will be overwritten
window.onload = function () { /* Can identify the label document Write (content): can only operate on body window When used in onload, it will overwrite the original content of the page and not the content added by itself. innerHTML: operating all closed tags will overwrite all the content in the original tag */ document.write(111); document.write(2222); document.body.innerHTML = '1234567'; document.write('123<br>456'); document.body.innerHTML = '<i>1234567</i>';}
Scope
-
concept
Function: reading and writing
Domain: area range
-
Scope: the range of variables and functions that can be read and written is divided by functions, which is called function scope
-
Global scope: under the script tag is the global scope
Variables declared by var are called global variables
The function declared by function is called a global function
Global variables and global functions can be read and written anywhere in the scope
-
Local scope: the region in function {} is the local scope
Variables declared by var are called local variables
The function declared by function is called a local function
Local variables and local functions only work in the current local scope. If {} occurs, they will be destroyed
-
var a = 20; // Global variable function sum() {/ / global function / / local scope console.log(a); / / global a}sum()// Global sumfunction s() {/ / local scope var num = 30; console.log (Num); / / local variable num function m() {console.log (1);} m();} s();// console. log(num); // Num is not defined. Num is undefined. An error is reported. / / m()// Error: m is not defined
Scope chain
Scope chain: a search method in js, which determines the upward search method of variables and functions
First, find variables and functions in their own scope. If they are found, they will be returned directly. If they cannot be found, they will go to the upper scope. If they have not found the global scope all the time, an error will be reported
var a = 20;function sum(){ console.log(a); // 20 // console.log(c);}sum();var b = 30;function s(){ var b = 21; console.log(b); // 21}s();
Variable lifting / pre parsing
js parser will execute js code in a certain order
-
Find var function, declare the variable declared by VaR in advance, but do not assign value; Store the whole function declared by function in memory;
- Parse line by line (from top to bottom)
In the first step, in the process of finding var, it is only declared that the assignment will be made when the = + = - = * = assignment operator is encountered
function only stores functions
var a = 20;sum();function sum() { console.log(1);}/* var a; function sum(){ console.log(1); } a = 20; sum();*/
Example 1
// console.log(a);// var a = 3;// console.log(typeof a);// function a() {// alert('1');// }// a();// var a = 4;// console.log(a);// a();// function a() {// alert(5);// };// a();// console.log(a);// --------- Parsing steps ----------- / / repeat the naming of variables and overwrite the previous pre parsed var a; var a; function a() { alert('1');} function a() { alert(5);}; console. log(a); // Line 47 function aa = 3;console.log(typeof a); // number// a(); // Error report a = 4;console.log(a); // 4// a(); // Error / / a ()// Error console log(a); // four
Example 2
// console.log(a);// console.log(d);// var a = 3;// var d = function a() {// alert('1');// };// console.log(a);// console.log(d);// a();// ------------ Parsing process ----------- var a; var d; console. log(a); // Aconsole log(d); // undefineda = 3; d = function a(){ alert('1');} console. log(a); // 3console. log(d); // Function 44a ()// A is 3 and cannot be called
Example 3
function fn(a) { // Formal parameter a = = = var a console log(a); var a = 3; console. log(a); // ---- Parsing process - / / var a// When the formal parameter is declared, var a executes / / console log(a); // undefined // a = 3; // console. log(a); // 3}fn();// ------ Parsing process ------ / * when calling a function, execute the internal code of the function. The scope of code execution is the local scope. When the execution environment changes, the pre parsing will be re executed and the code will be executed*/
Example 4
function fn(a) { // Formal parameter a = = = var a console log(a); var a = 3; console. log(a); // ---- Parsing process - / / var a// Var a is executed when the formal parameter is declared / / a = 2// Assign an argument to a formal parameter / / console log(a); // 2 // a = 3; // console. log(a); // 3}fn(2);// ------ Parsing process ------ / * when calling a function, execute the code inside the function. The scope of code execution is a local scope. When the execution environment changes, the pre parsing will be re executed, and the assignment of code arguments will be executed after the formal parameters are declared*/
Example 5
var a = 4;function fn(b) { console.log(a); var a = 3; console.log(a);};fn();console.log(a);// -----Parsing process ----- / * when calling a function, execute the code inside the function. The scope of code execution is a local scope. When the execution environment changes, the pre parsing will be re executed and the assignment of code arguments will be executed. After declaring the formal parameters, VAR * / / / var a// function fn(b) {// console.log(a);// var a = 3;// console.log(a);// };// a = 4;// fn();// /* // var b;// var a; Local variable / / console log(a); undefined// a = 3;// console. log(a); 3// */// console. log(a); // Global variable 4
Example 6
var a = 4;function fn(b) { console.log(a); a = 3; console.log(a);};fn();console.log(a);// -----Parsing process ----- / * when calling a function, execute the code inside the function. The scope of code execution is a local scope. When the execution environment changes, the pre parsing will be re executed and the assignment of code arguments will be executed. After declaring the formal parameters, VAR * / / / var a// function fn(b) {// console.log(a);// a = 3;// console.log(a);// };// a = 4;// fn();// /* // var b;// console. log(a); Global variable 4 / / a = 3// console. log(a); Global variable 3 / / * / / / console log(a); // Global variable 3
Example 7
var a = 4;function fn(a) { console.log(a); a = 5;};fn(a);console.log(a);// ----Parsing process - / / var a// function fn(a) {// console.log(a);// a = 5;// };// a = 4;// fn(a); // Global variable a = 4 / / / * / / FN (4)// var a; Var a in the function is the local variable / / a = 4; Assign an argument to a formal parameter / / console log(a); 4// a = 5;// */// console. log(a); // Global a 4
Example 8
function fn(a) { var s = a; s.name = 'Excellent employment';};var json = { name: 'Small u'};fn(json);console.log(json);// -----Parsing process - / / var JSON// Function fn (a) {/ / var s = a; / / s.name = 'excellent employment'; / /}// JSON = {/ / 'name': 'small U' / /}// fn(json); // Small U / / / * / / var a// var s;// A = {small U}// s = a; {xiaou} / / s.name = 'excellent employment' / / * / / / console log(json); // Employment
Function return value
Return value of function:
After each function is called, there will be a return result, which is the return value of the function
var variable = function name ();
When the return value is not set, undefined is returned by default
Set return value:
return value;
Usage scenario:
When the value inside the function is used outside the function, it needs to be set as the return value
function sum(){ alert(1);}var u = sum();console.log(u); // undefinedfunction s(){ return 30;}var m = s();console.log(m); // 30
var m = sum(1000);console.log(m);function sum(num) { // There is a variable sum var s1 = 0// Judge whether each number is an odd number for (VaR I = 1; I < = num; I + +) {/ / judge whether it is an odd number 2n + 1 to 2. If the remainder is 1, it is an odd number if (I% 2 = = 1) {/ / console.log (I); S1 + = I;}} console. log(s1); return s1;}// console. log(s1); // report errors
return
return function:
\1. Set return value
\2. The end code is in the function. As long as it encounters return, all the codes behind return will not be executed and will end directly
return returns multiple values:
\1. return and, when setting multiple return values, return the last data
\2. Multiple data in the array can be returned with object and array settings, and the specific value cannot be determined
It is suggested that object can clearly know what each data represents
var m = sum(1000);console.log(m); // Array object function sum(num) {/ / there is a variable and var s1 = 0; / / judge whether each number is an odd number for (VaR I = 1; I < = num; I + +) {/ / judge whether it is an odd number 2n + 1 to 2. If the remainder is 1, it is an odd number if (I% 2 = = 1) {/ / console.log (I); S1 + = I;}}// return s1,i; // Function encounters return end star / / console log(s1); // Don't execute / / return [S1, num, I]; return { 'sum': s1, 'num': num, 'i': i }}// console.log(s1); // report errors
Get non line style
ie678: element currentStyle. Attribute name
Standard (Chrome / FF / IE9): getcomputedstyle (element) Attribute name
// chrome// console. log(getComputedStyle(div). width); // 200px IE8 and below: the value of the property "getcomputedstyle" is null, undefined or not a Function object. / / the global Function is windowsole log(window.getComputedStyle); // ie8: undefinedconsole. log(div.currentStyle); // Standard: undefined / / console log(div.currentStyle.width); // 200px chrome: cannot read property 'width' of undefined / / add judgment to judge the current browser if(div.currentStyle) {/ / really / / IE console.log (div.currentstyle. Width); console.log (div.currentstyle. Color);} Else {/ / standard console.log (getcomputedstyle (DIV). Width); console.log (getcomputedstyle (DIV). Color);}
Packaging steps
-
Create an empty function
-
Duplicate code / object code
-
Home location call
-
Extraction parameters extract variable data from the top to the next line as parameters
-
Pass the parameter call to pass in whoever is pulled out
-
Set the return value to return the data to be used outside the function
-
Receive return value
Encapsulate non interline styles
var w = getStyle(div, 'width');console.log(w);var c = getStyle(div, 'color');console.log(c);var s = getStyle(span, 'fontSize');console.log(s);/* 1. Create an empty function 2 Repeat code / object code into 3 Call from original position 4 Extract parameters extract variable data from the top to the next line as parameter 5 Pass the parameter call to pass in whoever is pulled out 6 Set the return value to return the data to be used outside the function 7 Receive return value*/function getStyle(ele, attr) { // Ele: element / / attr: attribute / / add judgment to judge the current browser if (ele.currentStyle) {/ / really / / IE return ele. Currentstyle [attr];} Else {/ / standard return getComputedStyle(ele)[attr];}}
use
<!-- 1. Introduce public js file --><script src="./ujiuye.js"></script><script> // Get the element var div = document getElementsByTagName('div')[0]; var bg = getStyle(div, 'backgroundColor'); console. log(bg); console. log(getStyle(div, 'backgroundColor'));</ script>
timer
Timer: delay a piece of code for a period of time or how often it is executed
classification
-
Delay timer: setTimeout (function, time) time unit: ms
-
Interval timer: setinterval (function, time) unit: ms
Delay timer
Delay timer: setTimeout (function, time) time unit: ms
SetTimeout (function name, time) time unit: ms
It will only be executed once
Usage scenario: one-time advertisements that cannot be closed
Encounter: how long to wait and what to do
setTimeout(function(){ console.log(1);}, 3000);
// 1. Get the element var img = document getElementsByTagName('img')[0];// 2. Delay the timer setTimeout(s, 3000) after waiting for the page for 3 seconds// The function name is not followed by () function s() {img. Style. Display = 'inline block';}
Interval timer
Interval timer: setinterval (function, time) time unit: ms
Let the function call every once in a while
Every once in a while
Application: rotagram counter timer countdown
// 1 --- 10 every 1svar, n = 1; setInterval(function(){ console.log(n); n++;}, 1000);
Clear timer
Once the timer is turned on, it will not clear automatically and needs to be cleared manually
setTimeout— >clearTimeout(timeId)
setInterval— >clearInterval(timeId)
After the timer is turned on (after the timer starts), an ID will be returned, which is unique in the whole page
var variable = setInterval/setTimeout();
Variables are unique identifiers
var n = 10;var timer = setInterval(function () { console.log(n); n--; // Countdown does not exist if (n < 0) {n = 0; / / clear timer clearInterval(timer);}// Write to document in the page body. innerHTML = n;}, 1000); console. Log (timer, 'ID'); var t = setTimeout(s, 3000); // The function name is not followed by () function s() {console.log (10);} console. Log (T, 'ID 1');
be careful
-
clear is different from return. clear only clears the timer and does not block subsequent codes. Subsequent codes continue to execute
-
Each timer will have a unique identification, and multiple timers can be opened at a time
Math
console.log(Math); // Object console log(Math.PI); // πconsole.log(Math.floor(3.9999999)); // Round down and round off the decimal 3console log(Math.ceil(3.00000000001)); // Round up as long as there is a decimal recognized by js 4 / / console log(Math.ceil(3.000000000000000000000000001));// console. log(3.000000000000000000000000001); console. log(Math.abs(-10)); // Absolute value console log(Math.round(4.455555)); // Round to console log(Math.round(4.555555)); // Round to console log(Math.pow(2, 10)); // Power 1024console log(Math.pow(3, 2)); // Power 9console log(Math.sqrt(9)); // Open radical 3console log(Math.sqrt(8)); // Root opening No.: 2.8284271247461903console log(Math.max(30,2,3,4,1,3)); // Find the maximum value of a group of numbers console log(Math.min(30,2,3,4,1,3)); // Find the minimum value in a group / / random number math random()
random number
Math. Random() random number between 0-1
Math.random() * the random number between 0-number does not include 0 and number
Math. Random() * (Y - x) + X X represents a small value and Y represents a large value, excluding X and y
for(var i = 1; i < 6; i++){ // console.log(Math.random()); // console.log(Math.random() * 10); console.log(Math.random() * (30 - 20) + 20);}
Time object
Classification of objects
-
Native object: Number\String\Boolean\Object\Array\Function\Date\RegExp\Error three basic three complex three others
-
Global objects: window
-
Host object: DOM BOM
-
Built in object: Global (window, document) Math
Create time object
var date = new Date(); // Current time object
var variable name = new date (future time format);
// 1. Create time object var date = new Date()// Current time object console log(date); // Tue Dec 01 2020 10:26:29 GMT + 0800 (China standard time) console log(typeof date); // object
var fur = new Date(2020, 11, 12, 0, 0, 0); // Year, month, day, hour, minute and second. Month is a number. You need to use 0-11 to represent January December. var fur = new Date(2020, 11, 12); var fur = new Date('2020-12-12 0:0:0'); // ' Year, month, day, hour: minute: second '// When string, the month does not need to be minus 1var fur = new Date('2020 23:32:23 '); / /- The hyphen can be replaced with the special symbol console in all English characters log(fur);
Get time in a specific format
console.log(date.toString()); // Tue Dec 01 2020 10:26:29 GMT+0800 (China standard time) console log(typeof date.toString()); // stringconsole. log(date.toLocaleDateString()); // 2020/12/01console. log(date.toLocaleTimeString()); // 10:29:21 am console log(date.toDateString()); // Tue Dec 01 2020console. log(date.toTimeString()); // 10: 30:09 GMT + 0800 (China standard time)
Get single time
// Creation time: var date = new Date();console.log(date);console.log(date.getFullYear()); // Console log(date.getMonth() + 1); // Month 0-11 numbers indicate January December console log(date.getDate()); // Day console log(date.getDay()); // Sunday --- Saturday 0---6var week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; console.log(week[date.getDay()]); // Tuesday console log(date.getHours()); // Hour 10console log(date.getMinutes()); // Minute console log(date.getSeconds()); // Seconds / / milliseconds from 1970-1-1 to now 1s == 1000ms timestamp console log(date.getTime()); // Millisecond timestamp
Set / create time
/* 1. Create future time var variable name = new date (future time format);*/var fur = new Date(2020, 11, 12, 0, 0, 0); // Year, month, day, hour, minute and second. Month is a number. You need to use 0-11 to represent January December. var fur = new Date(2020, 11, 12); var fur = new Date('2020-12-12 0:0:0'); // ' Year, month, day, hour: minute: second '// When string, the month does not need to be minus 1var fur = new Date('2020 23:32:23 '); / /- The hyphen can be replaced with the special symbol console in all English characters log(fur);// 2. Separately set a certain time, month, day, hour, minute, second, millisecond var cur = new Date()// All get methods have set methods except cur setFullYear(2022); cur. setMonth(2); // Month is a number. You need to use 0-11 to represent January December cur setDate(28); cur. setHours(13); cur. setMinutes(0); cur. setSeconds(0);// Milliseconds directly represents a complete time cur setTime(1578654345678); console. log(cur);
Count down
/* Double Twelve Countdown: difference between current time and future time = future time - current time 1 Future time current time*/auto();// The page updates setinterval (auto, 1000) every 1s; Function auto() {var cur = new date(); console.log (cur); VAR fur = new date (2020, 11, 12, 0, 0, 0); console.log (fur); / / time difference = milliseconds of future time - milliseconds of current time; VAR Cha = fur. Gettime() - cur. Gettime(); console.log (CHA) ; // 900540033 / / 1s = 1000ms 1m = 60s 1H = 60m 1D = 24h / / sec var s = parseInt (CHA / 1000% 60); console. log(s); // Min var M = parseInt (CHA / 1000 / 60% 60); console. log(m); // Hour var H = parseInt (CHA / 1000 / 60 / 60% 24); console. log(h); // Day var d = parseInt (CHA / 1000 / 60 / 60 / 24); console. log(d); // The countdown document is displayed in the page body. InnerHTML = 'now there is still 12 left from double 12:' + add0(d) +'day '+ add0(h) +'hour' + add0(m) +'minute '+ add0(s) +'second';}
moment
moment. Time base of JS processing time
download
Baidu: momentjs cdn
Moment.js is a JavaScript date processing class library for parsing, checking, operating, and displaying dates.
https://www.bootcdn.cn/moment.js/
https://momentjs.bootcss.com/
classification
moment.js: uncompressed learning
moment.min.js: compression development
Use attention
All individual numbers must have a leading 0
Chinese characters are not allowed for symbols
Creation time
/* 1. Creation time */var date = moment(); // When there are no parameters, the current time created is var date = moment('2005-08-11 14:22:22 ')// String var date = moment ({year: 2003, month: 4, / / 5, day: 22, hour: 23, minute: 21, second: 10, millisecond: 999 / / MS}); console.log(date);
Format time
YYYY year
MM month
DD day
d week
HH hours
mm min
ss seconds
X contains only a timestamp of seconds
// Format time console log(date.format('YYYY-MM-DD HH:mm:ss'));console.log(date.format('YYYY MM DD HH: mm: Ss'); console. log(date.format('YYYY')); // Year console log(date.format('MM')); // Month console with leading 0 log(date.format('DD')); // Date console with leading 0 log(date.format('d')); // 0 - 6 represents Sunday to Saturday console log(date.format('HH')); // Hour console with leading 0 log(date.format('mm')); // Minute console with leading 0 log(date.format('ss')); // Second console with leading 0 log(date.valueOf()); // MS 10536168709999 console log(date.format('X')); // Time stamp 1053616870 with seconds only
Set / get
var date = moment();console.log(date.format('YYYY-MM-DD HH:mm:ss'));// Get / set console log(date.year()); // Get year date year(2012); date. set('year', 2022); // ' Attribute name ',' attribute value 'date set({ year: 2020}); console. log(date.format('YYYY-MM-DD HH:mm:ss'));//------- There is a similar usage console log(date.month()); console. log(date.date()); console. log(date.hour()); console. log(date.minute()); console. log(date.second()); console. log(date.day()); // Saturday, 0-6, 2 console log(date.daysInMonth()); // Days of the month in which the date is located console log(date.week()); // What week of the year is console log(date.dayOfYear()); // What day of the year is console log(date.quarter()); // What quarter of the year is console log(date.isLeapYear()); // Is it a leap year console log(date.toDate()); // Moment object -- > time object Tue Dec 01 2020 15:28:57 GMT+0800 (China standard time)
String
concept
String: a string is wrapped in pairs of single and double quotation marks
establish
- Literal creation: var variable = 'character';
- Cast: var variable = string (data);
- Constructor / instance creation: var variable = new string (data);
Difference: 1.2 creates a string type and 3 creates an object type
var str = '123456a';console.log(str);console.log(typeof str); // stringvar str1 = String(true);console.log(str1);console.log(typeof str1); // stringvar str2 = new String(false);console.log(str2); // {"false"}console.log(typeof str2); // object
length
length: string length
Subscript: a number starting from 0 from left to right
var str3 = 'Recently, Ding Zhen, a Tibetan guy living in Litang County, Ganzi Prefecture, Sichuan Province, was unexpectedly popular on the Internet because of a video of less than 10 seconds. He was not only hired as a tourism ambassador by the local government, but also triggered a boost upsurge of local cultural and tourism institutions. Through Ding Zhen's window, more people can learn about the scenic spots in Sichuan and even the whole country. Netizens have said that "this is the best way to open wanghong". Tonight, let's start with this Tibetan guy. The Internet provides a stage for everyone to show themselves. Not a few people are popular because of a sentence, an expression and an action, but Ding Zhen triggered such a large-scale Internet boom and even won the support of the spokesman of the Ministry of foreign affairs call Yes, but it is also rare. Some people say that Ding Zhen's popularity stems from his ultra-high appearance and handsome appearance. Others say that Ding Zhen's simplicity and innocence are particularly moving. In fact, these just let him have the potential of net popularity. What really makes him the "top flow" is his love for his hometown and life, which makes people feel the self-improvement force growing up in adversity. It is the elements such as snow mountains, white clouds and Tibetan costumes in the lens, which shows a colorful and three-dimensional China, awakens people's longing for poetry and distance, and remains the pure nature after his popularity, Let people see a pure heart.';console.log(str3.length); //
Specifies the character of the subscript
charAt: string charAt (subscript)
[]: String [subscript]
console.log(str3.charAt(51));console.log(str3[51]);
Specifies the ASCII value of the subscript character
charCodeAt: string charCodeAt (subscript);
0----48 9—57
A----65 Z—90
a----97 z—122
console.log(str3.charCodeAt(51));
string comparison
String comparison: compare the ASCII values of each character from left to right. If the size is compared, it ends
console.log('100000000000' < '2'); // trueconsole.log('100' < '1'); // false 48 < 0
lookup
indexOf
-
Syntax: indexOf: string indexOf('matched character ', starting subscript);
The initial subscript can be transferred or not
-
Find rules:
Find the first position of the character in the string, match it from left to right, find it and return the subscript, if not, return - 1
The starting subscript means to start from the position of this subscript and search from left to right
var str = 'abcdefabcdef';console.log(str.indexOf('a')); // 0console.log(str.indexOf('g')); // -1console.log(str.indexOf('a', 3)); // 6
lastIndexOf
-
Syntax rule: lastIndexOf: string lastIndexOf('matched character ', starting subscript);
The initial subscript can be transferred or not
-
Find rules
Find the first position of the character in the string, match it from right to left, find it and return the subscript, if not, return - 1
The starting subscript means to start from the position of this subscript and search from right to left
console.log(str.lastIndexOf('a')); // 6console.log(str.lastIndexOf('a', 4)); // 0
intercept
substring
substring: string substring (start subscript, end subscript);
No parameters: intercepts and returns the entire string
Pass a parameter: intercept the character containing the starting subscript from the starting subscript to the end of the string
Pass two parameters:
Start subscript < end subscript: from the start subscript to the end subscript, the characters containing the start subscript do not contain the characters of the end subscript
Start subscript > end subscript: swap positions and intercept
If one of them is negative: the negative number becomes 0, refer to the above rules
var str = 'ABCDEFGHIJK';console.log(str.substring());console.log(str.substring(3)); // DEFGHIJKconsole.log(str.substring(3, 6)); // DEF console.log(str.substring(6, 3)); // DEF console.log(str.substring(3, -4)); // 0-3 ABC
slice
slice: string slice (start subscript, end subscript);
No parameters: intercepts and returns the entire string
Pass a parameter: intercept the character containing the starting subscript from the starting subscript to the end of the string
Pass two parameters:
Start subscript < end subscript: from the start subscript to the end subscript, the characters containing the start subscript do not contain the characters of the end subscript
Start subscript > end subscript: returns an empty string
If one of them is a negative number (end): it means that there are several characters from right to left
console.log(str.slice());console.log(str.slice(3)); // DEFGHIJKconsole.log(str.slice(3, 6)); // DEFconsole.log(str.slice(6, 3)); // Empty console log(str.slice(3, -3)); // DEFGH
substr
substr: string substr (starting subscript, intercepted length)
No parameters: intercepts and returns the entire string
Pass a parameter: intercept the character containing the starting subscript from the starting subscript to the end of the string
Pass two parameters: how many bits are intercepted from the starting subscript
console.log(str.substr());console.log(str.substr(3)); // DEFGHIJKconsole.log(str.substr(3, 6)); // Intercept 6 characters of DEFGHI from subscript 3
toggle case
Uppercase: string toUpperCase();
Lowercase: string toLowerCase();
Application: case insensitive verification code
var str = 'ASDFGHJasdfghj';console.log(str);console.log(str.toUpperCase());console.log(str.toLowerCase());
replace
Replace: replace content with new characters
str.replace('content to replace '/ regular,' new character '/ function);
Only one character can be replaced at a time
var str = 'abcabc';console.log(str.replace('a', '***')); // ***bcabc
division
Splits the string according to the delimiter
String split('separator ');
The delimiter can be any character
Splits a string into an array and returns
Array splicing method:
join: array join('connector ');
The connector defaults to,
Connectors can be all characters, including labels
Returns an array as a string
var str = '12341234';console.log(str.split('1'));console.log(str.split('1').join('****'));console.log(str.split('1').join('<br>'));var s = str.split('1').join('<b>123</b>');document.body.innerHTML = s;
trim
trim: remove the space around the string
String trim();
var str = ' 123 121 ';console.log(str);console.log(str.trim());
array
concept
Array concept: a container used to store an indefinite number of indefinite types of data
statement
Literal
Literal quantity: var variable = [data, data,...];
var arr = [1,2,3,4];console.log(arr);
Constructor / instance
var variable = new array (data);
Data: two or more: each item in the array
If there is only one item and it is a number: the length of the array, there are several empty(undefined) in the array
var arr1 = new Array(1,2, 'a', true);console.log(arr1);var arr2 = new Array(4);console.log(arr2);console.log(arr2.length);
length
Length: array Length the length of the array
console.log(arr2.length);arr2.length = 10; // You can change the item console in the array by changing the length log(arr2); arr.length = 2; console. log(arr); // The data deleted by length cannot be found
Elements and indexes
Element: each value item in the array
Index: the index of each value in the array
console.log(arr2[3]);console.log(arr[0]);
Stack method
push: add one or more items to the end of the array and return the length of the array
pop: deletes an item from the end of the array and returns the deleted item
unshift: adds one or more items to the beginning of the array and returns the length of the array
shift: deletes an item from the beginning of the array and returns the deleted item
Will change the original array
var b = [1,2,4];var arr = ['a', 'b', 1, 2, 'c', 4];var len = arr.push(3, b, 4, 6);console.log(arr);console.log(len);var del = arr.pop();console.log(arr);console.log(del);var len1 = arr.unshift(10, 9, 8);console.log(arr);console.log(len1);var del1 = arr.shift();console.log(arr);console.log(del1);
splice
grammar
splice: a versatile array method
Syntax: arrays Splice (starting subscript, number of deleted items, item 1, item 2,..., item n);
Add: array Splice (initial subscript, 0, item 1, item 2,..., item n);
Deleting: arrays Splice (starting subscript, number of deleted items);
Modifying: arrays Splice (starting subscript, number of deleted items, item 1,..., item n)
Delete several, add several
Return value: returns an array of deleted items
var arr = [0,1,2,3,4];// Little Joe arr.splice(2, 0, 'Little Joe', 'Big Joe'); console.log(arr); // [0, 1, "Little Joe", "Big Joe", 2, 3, 4]arr.splice(4, 3);console.log(arr); // [0, 1, "Xiao Qiao", "Da Qiao"] var arr1 = arr.splice(0, 2, 'Lv Bu', 'Diao Chan'); console.log(arr); // ["Lv Bu", "Diao Chan", "Xiao Qiao", "Da Qiao"] console log(arr1);
duplicate removal
var arr = [1,2,3,3,4,4,5,4,4,1,2,1,1,2333334,51,2,243,1];console.log(arr);/* Compare the first item (0) with each subsequent item (1). If there is a duplicate, delete the duplicate item. Compare the second item (1) with each subsequent item (2). If there is a duplicate, delete the duplicate item. Compare the third item (2) with each subsequent item (3), If there is a duplicate, delete the duplicate item later Compare the last item with each of the following items. If there is a duplicate, delete the duplicate item*/for(var i = 0; i < arr.length; i++){ // For (VaR, j = I + 1; J < arr.length; j + +) {console.log (arr [i], arr [J]); if (arr [i] = = arr [J]) {/ / delete the duplicate item (j) arr.splice(j, 1); / / this cycle needs one more j --;}}} console. log(arr);
algorithm
Select Sorting Algorithm
Select sort:
Take out one item and compare it with each item in the back. If the latter item is smaller than the front one, swap the position
Process:
Compare the first item (0) with each subsequent item (1). If the previous item is larger than the subsequent item, swap the position
Compare the second item (1) with each subsequent item (2). If the previous item is larger than the latter item, swap the position
Compare the third item (2) with each subsequent item (3). If the previous item is larger than the latter item, swap the position
...
Compare the last item with each subsequent item. If the previous item is larger than the latter item, swap the position
var arr = [1, 3, 1, 4, 2, 5, 6, 3232, 1,32];for(var i = 0; i < arr.length; i++){ // For (VaR J = I + 1; J < arr.length; j + +) {console.log (arr [i], arr [J]); / / if the preceding item is larger than the following item, swap the position if (arr [i] > arr [J]) {/ / the intermediate item var temp = arr [i]; arr [i] = arr [J]; arr [J] = temp;}}} console. log(arr);
Bubble algorithm sorting
Compare the two adjacent items. If the front one is larger than the rear one, swap the positions
How many lengths does the array have and how many times does it go
var arr = [3, 1, 2, 4, 6, 1, 7];for (var i = 0; i < arr.length; i++){ // Comparison of two adjacent items 0 1 2 3 4 for (VaR J = 0; J < arr.length - I; j + +) {/ / adjacent console.log (arr [J], arr [J + 1]); if (arr [J] > arr [J + 1]) {/ / exchange position var temp = arr [J]; arr [J] = arr [J + 1]; arr [J + 1] = temp;}}} console. log(arr);
sort
Sort: array sort();
Sort by string encoding by default
Array Sort (parameter);
The argument must be a function. The function has two formal parameters
First parameter - the second parameter is sorted from small to large
Second parameter - the first parameter is sorted in descending order
var arr = [3, 4, 5, 1, 2, 5, 6];arr.sort();console.log(arr); // [1, 2, 3, 4, 5, 5, 6]var arr = [32, 23, 1, 32, 23, 4, 6, 8, 54, 32];// arr.sort();// console.log(arr); // [1, 23, 23, 32, 32, 32, 54] / / the parameter must be a function. The function has two parameters arr.sort (function (a, b) {/ / return a - B; / / the first parameter - the second parameter is sorted from small to large by default return b - a; / / the second parameter - the first parameter is sorted from large to small}); console.log(arr);
Array method
join
join: connect each item of the array with a connector and return a string, which is linked by default
Connectors can be all characters
var arr = [1,2,3,45,6];console.log(arr.join());console.log(arr.join('-'));
concat
concat: concatenate multiple arrays or items into an array concat (item, item 1,...);
Returns the array after splicing
The original array will not be changed
var arr1 = [4,5,6];console.log(arr.concat(arr1));console.log(arr, arr1);
reverse
Reverse: flip the array reverse();
Will change the original array
```javascript
arr.reverse();
console.log(arr);
arr.reverse();
console.log(arr);
```
indexOf/lastIndexOf
indexOf/lastIndexOf: search, which is exactly the same as the string method
The item to be found can only be found when it is equal to the item in the array (= = =)
Returns the subscript of the corresponding item if found, and - 1 if not found
var arr = [1,2,3,5,6];console.log(arr.indexOf(1)); // 0console.log(arr.indexOf('1')); // -1console.log(arr.lastIndexOf(6)); // 4
slice
slice: This is the only one in the interception array
Slice: array slice();
A rule that is exactly the same as a string
Interception rules:
- None is passed back to all
- Pass a parameter to intercept from the current starting subscript to the last
- Pass two parameters: intercept from the current start subscript to the end subscript, including the start subscript and excluding the end subscript
- If start subscript > end subscript, return null directly
- When the ending subscript is negative, it means that the following items are not allowed
console.log(arr.slice()); // None is passed back to all consoles log(arr.slice(3)); // 5.6 pass a parameter from the current starting subscript to the last console log(arr.slice(3, 4)); // 5. Pass two parameters from the current start subscript interception to the end subscript, including the start subscript and not including the end subscript console log(arr.slice(6, 4)); // If the start subscript > end subscript of an empty array, it will directly return to the empty console log(arr.slice(1, -1)); // 2 3 5 when the ending subscript is negative, it means that the following items are not allowed
Iterative method
- every: make a judgment on each item of the array. If each item meets this judgment condition, the return result is true, and one is false is false
All true is true and one false is false&&
Array every(function(value, index, array){});
Three parameter names are not fixed
index: subscript
value: item
Array: array itself
If the return value is not set, it returns undefined by default
var arr = [1, 2, 3, 4];var m = arr.every(function (v, i, a) { console.log(i, v, a); // return v > 0; return v > 3;});console.log(m);
- some: make a judgment on each item of the array. If one item meets this judgment condition, the return result is true, and all false is false
All false is false and one true is true||
Array some(function(value, index, array){});
var n = arr.some(function(v, i, a){ console.log(i, v, a); // return v > 0; return v > 3;});console.log(n);
-
Filter: select the qualified data to form a new array to return and filter the data
var mn = arr.filter(function(v, i, a){ console.log(i, v, a); // return v > 2; return v > 0;});console.log(mn);
-
map: return a new array and form the returned values into a new array
var ab = arr.map(function(v, i){ console.log(v, i); // return 1; return v * v * v;});console.log(ab);
-
forEach: just a simple loop with no return value for array
var l = arr.forEach(function(v, i){ console.log(v, i); // v = i + 1; The original array will not be affected / / arr [i] = V * V; return 20;}); console. log(arr); console. log(l);
algorithm
Quick sort
-
Find the middle subscript first
-
Found the item store for the middle subscript
-
And delete it from the original array
-
Declare two empty arrays to store values smaller than the middle and larger than the middle
-
Traverse each item in the array. If the value is smaller than the middle item, put it in left. If the value is larger or equal than the middle item, put it in right
-
Repeat for the left and right arrays
-
Concatenate the left array with the middle item and the right array
var arr = [2, 3, 5, 21, 54, 12, 43];function qs(shuzu) { // Condition for function end if (Shuzu. Length < = 0) {return Shuzu;}// 1. Find the middle subscript var num = math floor(shuzu.length / 2); console. log(num); // 2. First find the item storage of the middle subscript var Val = Shuzu [num]; console. log(val); // 3. And delete Shuzu. In the original array splice(num, 1); console. log(shuzu); // 4. Declare an empty array var left = [], right = []// 5. Traverse for (VaR I = 0; I < Shuzu. Length; I + +) {if (Shuzu [i] < VAL) {left. Push (Shuzu [i]);} else { right.push(shuzu[i]); } } return qs(left). concat(val, qs(right));} var a = qs(arr); console. log(a);
Chinese sorting
Chinese sorting: data Localsecompare (data 1, language);
Sort the data in combination with sort
en: English
English: b from z to a, a from a to z
// English: B from z to a, a from a to zvar, a = 'Zhang San'; var b = 'Li Si'; console. log(a.localeCompare(b, 'zh')); console. log(b.localeCompare(a, 'zh')); Var arr = [{Name: 'Wu Lixin', Num: 78}, {Name: 'Tang Wenbo', Num: 38}, {Name: 'Lu Wenbo', Num: 58}, {Name: 'Deng Junjian', Num: 97}, {Name: 'Liu ji'ang', num: 56}, {Name: 'Li Junan', Num: 78}, {Name: 'Qu Xiaoyue', Num: 98}, {Name: 'Fu Qiuping', Num: 79}]; Arr.sort (function (a, b) {console.log (a, b); / / sort by name / / a-b from small to large, b-a from large to small / / Chinese: B from z to a, a from a to z / / return b.name.localecompare (a.name, 'zh'); return a.name.localecompare (b.name, 'zh');}); console. log(arr);
DOM
introduce
DOM: Document Object Model
DOM is a standard interface for manipulating pages specified by W3C
The browser renders the page to generate a DOM tree
html
head body
meta title a div p em
text href src
Get child nodes
-
children's non-standard attributes get all label nodes ie678 label nodes and comment nodes from the standard browser
-
childNodes standard attribute all child nodes (label + line feed) ie678 label nodes in the standard browser
-
Syntax: elements The children element childNodes
var ul = document.getElementsByTagName('ul')[0];console.log(ul.children); // HTMLCollectionconsole.log(ul.childNodes); // NodeList
Node attributes
Node name: nodeName: each tag name is capitalized A LI DIV
Node type: nodeType: number 1 of 1-12 - label 2 - attribute 3 - content
Node content: nodeValue: only text has content
// for(var i = 0; i < ul.children.length; i++){// console.log(ul.children[i]);// console.log(ul.children[i].nodeName); // LI// console.log(ul.children[i].nodeType); // 8 3 1// console.log(ul.children[i].nodeValue); // null // }for(var i = 0; i < ul.childNodes.length; i++){ console.log(ul.childNodes[i]); console.log (ul.childNodes[i].nodeName); // LI console. log(ul.childNodes[i].nodeType); // console. log(ul.childNodes[i].nodeValue); // if(ul.childNodes[i].nodeType == 1) {/ / if the label has no content, the text node will have content. If it is judged that the node is a label node, console.log(ul.childNodes[i].childNodes); / / get all the child nodes in the label node console.log(ul.childNodes[i].childNodes[0]); / / get the text node console.log (UL. ChildNodes [i]) .childNodes[0]. nodeValue); // Get the content of the text node in the label node}
Parent node
-
Get direct parent node: element parentNode
-
Parent node with positioning attribute: element offsetParent if there is no parent element with positioning attribute, the result is body
// Get the third livar Li = document getElementsByTagName('li')[2]; console. log(li);/* Get parent node: 1 Get direct parent node: element parentNode 2. Parent node with positioning attribute: element If there is no parent element with positioning attribute for offsetparent, the result is body * / console log(li.parentNode); console. log(li.offsetParent);
Get other nodes
First child node
First child node:
Parent node firstChild: ie8 label node standard: line feed
Parent node firstElementChild: ie8 undefined standard: label node
Line feed solution:
-
Delete line breaks
-
Compatibility: one attribute has and one attribute does not (undefined false null...)
Put what you don't have in front of you and what you have behind you
Parent node firstElementChild - parent node firstChild
console.log(ul.firstChild, ul.firstElementChild);console.log(ul.firstElementChild || ul.firstChild);
Last child node
Parent node lastChild: ie8 label node standard: line feed
Parent node lastElementChild: ie8 undefined standard: label node
Compatibility: parent node lastElementChild - parent node lastChild
console.log(ul.lastChild, ul.lastElementChild);console.log(ul.lastElementChild || ul.lastChild);
Previous sibling node
Previous sibling node:
Node previousSibling: ie8 label node standard: line feed
Node previousElementSibling: ie8 undefined standard: label node
Compatibility: nodes previousElementSibling node previousSibling
console.log(li.previousSibling, li.previousElementSibling);console.log(li.previousElementSibling || li.previousSibling);
Next sibling node
Next sibling node:
Node nextSibling: ie8 label node standard: line feed
Node Nextlementsibling: IE8 undefined standard: label node
Compatibility: nodes Nextlementsibling node nextSibling
console.log(li.nextSibling, li.nextElementSibling);console.log(li.nextElementSibling || li.nextSibling);
Create node
-
Create label node: document CreateElement ('tag name ')
-
Create text node: document CreateTextNode ('content ')
-
Add text node to label node: parent node AppendChild (child node);
-
Add label node to parent element: parent node AppendChild (child node);
var ul = document.getElementsByTagName('ul')[0];var li = document.createElement('li');console.log(li);var txt = document.createTextNode('00001');console.log(txt);li.appendChild(txt);console.log(li);ul.appendChild(li);
Append node
Append child node to parent node (last):
Parent node AppendChild (child node);
If an existing element in the page is added, the physical displacement is generated (change the position);
var ul = document.getElementsByTagName('ul')[0];var li = document.createElement('li');console.log(li);var txt = document.createTextNode('00001');console.log(txt);li.appendChild(txt);console.log(li);ul.appendChild(li);var ul1 = document.getElementsByTagName('ul')[1];ul1.appendChild(li);
Insert before an element
Parent node Inserbefore (new node, reference node);
var li1 = document.createElement('li');// Setting content: Li1 innerHTML = '1234'; ul1. insertBefore(li1, li);
Remove node
- Remove itself: node remove(); It will delete itself and all its child nodes
- Remove child node: node Removechild (child node); The child node and all of its nodes are removed
ul1.removeChild(li1);ul.remove();
Replace node
Replace child node: parent node Replacechild (new node, reference node);
var li2 = document.createElement('li');li2.innerHTML = '<b>12345</b>';ul1.replaceChild(li2, li);
Clone node
Cloning: nodes cloneNode(boolean);
true: clone the node and its contents
false / no transfer: Clone nodes only
Return the cloned node, which needs to be appended to the parent element again before it can be seen in the page
// var ul2 = ul1.cloneNode();// var ul2 = ul1.cloneNode(false);var ul2 = ul1.cloneNode(true);console.log(ul2);document.body.appendChild(ul2);
Get element new method
ie8+:
document.querySelector('css selector ') gets the first element that matches the selector
document.querySelectorAll('css selector ') gets a collection of all elements that match the selector
The same feature as id is static. You can get it if you have it on the page when you get it. You can't get it if you don't have it when you get it
var txt = document.querySelector('#txt');console.log(txt);var boxes = document.querySelectorAll('.box');console.log(boxes); // NodeList / / get the class names box and Avar boxa = document querySelectorAll('.box.a'); console. log(boxa);// Get the class name a and id TXT / / combination selector var all = document querySelectorAll('.a,#txt'); console. log(all); var li = document. createElement('li'); li. innerHTML = '12345'; li. className = 'aaaa'; var aa = document. querySelector('.aaaa'); var ul = document. querySelector('ul'); console. log(aa); // Get the newly added node nullul appendChild(li); console. log(aa); // null
Operation properties
-
Get attribute: element Attribute name element ['attribute name']
console.log(box.id);console.log(box.className);
-
Setting attributes: elements Attribute name = value; Element ['attribute name'] = value;
box.id = 'oBox';box.className = 'oTxt';
Note: 1.2 the user-defined attribute written on the label cannot be obtained. The user-defined attribute of the operation cannot be obtained
-
Get attribute: element getAttribute('attribute name '); Write the class name directly to class
console.log(box.getAttribute('class')); // oTxtconsole.log(box.getAttribute('tag')); // 1
-
Setting attributes: elements setAttribute('attribute name ',' attribute value ');
box.setAttribute('class', 'a b');box.setAttribute('a1', true);
-
Remove attribute: element removeAttribute('attribute name ');
box.removeAttribute('tag');
Get table elements quickly
// Get table elements quickly / / 1 Get tablevar table = document first getElementsByTagName('table')[0]; console. log(table); console. log(table.tHead); // Table header console log(table.tFoot); // Table footer console log(table.tBodies); // Set of table body / / the table in the table consists of rows. Console log(table.rows); // A collection of all rows in the whole table / / obtain the row console. In the specified table body log(table.tBodies[0].rows); // All the rows in the first table body / / the rows in the table are composed of cells. You can only obtain all the cells in the row through the row console log(table.rows[0].cells); // Set of all cells in the first row console log(table.tBodies[0].rows[0].cells); console. log(table.cells); // undefinedconsole. log(table.tBodies[0].cells); // undefined
form
Get form elements quickly
Quickly get the elements in the form: form Name value
Value: form Name value value
// 1. formvar form = document.getElementsByTagName('form')[0];// 2. Quickly get the elements in the form: form Name / / value: form Name value valueconsole.log(form.user);console.log(form.user.value);console.log(form.sex); // RadioNodeList set console log(form.sex.value); // nanconsole. log(form.hobby); // Radionodelist / / unable to pass form Name value Value. / / how to obtain the value of the check box var arr = []; for(var i = 0; i < form.hobby.length; i++){ if(form.hobby[i].checked == true){ arr.push(form.hobby[i].value); }} console. log(arr);
Form Events
onsubmit
When the button is clicked, the form submission is triggered
return true: the form can be submitted
return false: the form cannot be submitted
Form form element onsubmit = function(){}
var form = document.getElementsByTagName('form')[0];console.log(form);// Add click event console to the submit button log(form.sub); form. sub.onclick = function(){}form. Onsubmit = function() {console. Log (1); / / return false; / / if (form. User. Value = = '' || form. Pass. Value = = '') {alert ('Please fill in all information '); return false;}}
onreset
Form onreset
When the form is reset
return true: the form can be reset
return false: the form cannot be reset
// Reset event form Onreset = function() {/ / if both the name and password are entered, reset, otherwise do not reset if (form. User. Value! = '' & & form. Pass. Value! = '') {return true;} else { return false; }}
onfocus
Elements in the form onfocus
An event is triggered when the input box gets the focus
form.user.onfocus = function(){ this.style.background = 'pink';}
onblur
Element onblur
An event is triggered when the input box loses focus
form.user.onblur = function(){ this.style.background = 'green';}
onchange
Element onchange
Triggered when the input box loses focus and the content changes from the last time
form.pass.onchange = function(){ this.style.background = 'orange';}
oninpu/onpropertychange
Element oninput/onpropertychange
Trigger while entering in the input box
// Trigger while inputting / / the event can be connected, which means that the same event handler function form. Is triggered pass. oninput = form. pass. onpropertychange = function(){ console.log(this.value);}
Form method
Form method:
Resetting: forms reset();
Submit: forms submit();
Form element method:
Focus: elements focus();
Out of focus: element blur();
Automatic selection: elements select();
var divs = document.getElementsByTagName('div');var form = document.getElementsByTagName('form')[0];console.log(divs);// Click submit divdivds [0] Onclick = function() {/ / if both user name and password are entered, you can submit if (form. User. Value! = '' & & form. Pass. Value! = '') {form. Submit();} Else {console.log ('incomplete information ');}}// Click Reset. / / if the user name or password is reset divs [1] onclick = function(){ if(form.user.value != '' || form.pass.value != ''){ form.reset(); } Else {console.log ('No reset required ');}}// Click the focus user name input box to focus on divs [2] onclick = function(){ form.user.focus();}// Wait for 10s for the user name input box to lose focus. / / setTimeout (function() {/ / console. Log (1); / / form. User. Blur(); / /}, 10000)// Wait for the page 3s and let the input box automatically select setTimeout (function() {/ / form. User. Select(); form. Sex [1]. Select();}, 3000);
BOM
Basic information
BOM: Browser Object Model
Core: window
window is an object supported by any browser
\1. Interface used to access browser in JS
\2. Global window in ES
All global variables and functions in the whole page belong to window
Global variable: an attribute of window
Global function: a method of window
console.log(window);var a = 20;console.log(a);console.log(window.a);function getNum(){ console.log(a);}getNum();window.getNum();// alert('123');window.alert('345');
System dialog
-
Warning box: alert("pop up content");
-
With confirm cancel button: confirm (pop-up content);
With return value true – OK false – cancel
- Dialog box with input box: prompt (prompt content, default value); The default value is not transmitted, and the input box is empty
With return value
OK: returns the contents of the input box
Cancel: null
Prompt the user or select jump information
// var c = confirm('agree to the agreement ')// console. log(c);// If (C = = false) {/ / console.log ('the user does not agree to this Agreement '); / /} / / the dialog box in the input box var p = prompt('Please enter the page you want to jump to', 10);console.log(p);
open and close
open
Open a new page
Open (address, opening method, width and height of the new page, whether to replace the history);
Opening method:_ self _blank
Set the width and height of the new page:_ blank
Return to the window of the new page
var span = document.querySelector('span');var w = null;span.onclick = function(){ w = open('http://www.ujiuye.com', '_blank', 'width=200px,height=1000px', true); console.log(w);}
<!-- Intra line cannot be omitted window --><span onclick="window.open('http://www.ujiuye. Com ') "> this is another new page</span>
close
close(): not prefixed with / window means to close the current page
You can also close other pages
var btn = document.getElementsByTagName('button')[0];btn.onclick = function(){ // close(); // window.close(); w.close();}
<button>Close current page</button><button onclick="window.close()">Close page in line</button>
location
/* location BOM One of the most useful objects in. It stores some information about the current window and provides some navigation functions. location is an object attribute of window and an attribute of document*/console.log(location);console.log(location.hash); // Hash value, hash #+ content console log(location.href); // Full address file:///E:/1026/day10/08%20location.html#123console.log(location.protocol); // Protocol HTTP HTTPS fileconsole log(location.host); // Server name + port number 127.0.0.1: 5500console log(location.hostname); // Server name 127.0.0.1console log(location.port); // Port number 5500console log(location.pathname);// File address / Day10 / 08% 20location htmlconsole. log(location.search); // Search content+ / / refresh the page location reload();// Page Jump window Location = address; location. Href = address; document.onclick = function(){ // location.reload(); // window.location = 'http://www.ujiuye.com'; location.href = 'http://www.baidu.com ';}
history
history: history stores the browsing records of users
Back: back one page
Forward: forward one page
go: forward and backward refresh
Go (number): 0 – refresh positive number - forward several pages negative number - backward several pages
/* history: History storage user's browsing record back: back one page forward: forward one page go: forward and backward refresh go (number): 0 -- refresh positive number -- forward several pages negative number -- backward several pages*/console.log(history);// Wait for 3s to advance a page setTimeout (function() {/ / history. Forward(); history. Forward (1);}, 3000);
Three width and height
client
Visible width and height: client
clientWidth/clientHeight: visual width / visual height content + padding
clientLeft/clientTop: width of left / top border
Width and height of the current viewing area:
document.documentElement.clientHeight/clientWidth
var div = document.querySelector('div');console.log(div);console.log(div.clientHeight, div.clientWidth);// 215(200 + 10 + 5) 235(200 + 25 + 10)console.log(div.clientLeft, div.clientTop);console.log(document.documentElement.clientHeight, document.documentElement.clientWidth);
offset
Duty width and height: offset
offsetHeight/offsetWidth: occupation height / occupation width content + padding + border
offsetTop: the distance between the current element and the parent element with positioning attribute. If the parent element is not positioned, the distance from the top of the body
offsetLeft: the distance between the current element and the parent element with positioning attribute. If the parent element is not positioned, the distance to the left of the body
console.log(div.offsetHeight, div.offsetWidth); // 235 270console.log(div.offsetLeft, div.offsetTop);// 5 30
scroll
Actual width and height: scroll
scrollHeight/scrollWidth: the actual width and height of the element
scrollTop/scrollLeft: the distance the element is scrolled
Page scrolling distance:
document.documentElement.scrollTop/scrollLeft
document.body.scrollTop/scrollLeft before Google 75
Compatibility:
document.documentElement.scrollTop || document.body.scrollTop
console.log(div.scrollHeight, div.scrollWidth);// div.onscroll = function(){// console.log(div.scrollTop, div.scrollLeft);// }window.onscroll = function(){ // console.log(document.documentElement.scrollTop, document.body.scrollTop); console.log(document.documentElement.scrollTop || document.body.scrollTop);}
summary
/* client: Visual width and height clientwidth / clientheight: content + padding offset: space width and height offsetHeight / offsetwidth: content + padding + border offsettop / offsetleft: distance from parent element with positioning attribute scroll: scrolltop / scrollleft: height / width of page / element being rolled up visual width and height of window: document documentElement. Scrolling distance of clientwidth / clientheight page document documentElement. scrollTop || document. body. Scrolltop scrolltop / scrollleft can be obtained or assigned. Other values can only be obtained*/
Lazy loading
Lazy loading: the picture will be displayed wherever the page scrolls
-
Layout: 1.1 img must have width and height space. The address of 1.2 img is written on a custom attribute
-
js
2.1 where the page scrolls, the picture will be displayed. When the picture enters the page, it will be displayed
Page scrolling distance + visual height of the screen > = distance of the element from the top of the page
2.2 when entering the page, the first screen needs to be displayed first
2.3 when the screen size changes, the picture of the current screen is displayed
window.onload = function () { /* Lazy loading: the picture will be displayed wherever the page scrolls. 1 Layout: 1.1 img must have a width height space. The address of 1.2 img is written on a custom attribute. 2 JS 2.1 where the page scrolls, the picture will be displayed. When the picture enters the page, the page scrolling distance + visual height of the screen > = the distance between the element and the top of the page. 2.2 when entering the page, the first screen needs to be displayed first. 2.3 when the screen size changes, the picture of the current screen will be displayed */ // 2.1 the picture will be displayed wherever the page scrolls to / / img var IMGs = document getElementsByTagName('img'); console. log(imgs); // var st = document. documentElement. scrollTop || document. body. scrollTop; // // console. log(st); // var ch = document. documentElement. clientHeight; // // console. log(ch); // // Judge whether each image complies with the above rules / / for (VaR I = 0; I < IMGs. Length; I + +) {/ / if (st + CH > = IMGs [i]. Offsettop) {/ / / / set the address of the image / / imgs[i].src = imgs[i].getAttribute('nsrc '); / /} showimg()// Scroll window onresize = window. onscroll = function () { showImg(); } Function showimg() {var st = document.documentelement.scrolltop | document.body.scrolltop; / / console.log (st); VAR ch = document.documentelement.clientheight; / / console.log (CH); / / judge whether each image complies with the above rules console.log (IMGs [0]. Offsettop); / / if (st + CH > = IMGs [0]. Offsettop) {/ / / / set the address of this picture / / IMGs [0]. SRC = IMGs [0]. Getattribute ('nsrc '); / /} for (VaR I = 0; I < IMGs. Length; I + +) {if (st + CH > = IMGs [i]. Offsettop) {/ / set the address of this picture imgs[i].src = imgs[i].getAttribute('nsrc') ; } } }}
resize
Screen size change event
window.onresize = function(){ console.log(1);}
Event object
concept
When an event is triggered, the browser will store some information related to the current event and the position of the mouse on an object, which is the event object
Global: event
Lower version ff: passed in as the first parameter of the event
var div = document.querySelector('div');div.onclick = function(evs){ console.log(event); // MouseEvent console.log(window.event); // MouseEvent console.log(evs); // Compatibility: put the multi-purpose in front of VaR EV = window event || evs; console. log(ev);} document. oncontextmenu = function(evs){ var ev = window.event || evs; console.log(ev.type); console.log(ev.target || ev.srcElement);}
Event object properties
console.log(ev.type); // Event type console log(ev.target || ev.srcElement); // The trigger source of the event console log(ev.target, ev.srcElement); // The trigger source of the event console log(ev.clientX, ev.clientY); // Position of the mouse from the visible area of the screen (X -- left y -- top) console log(ev.pageX, ev.pageY); // The position of the mouse from the upper left corner of the page (body) console log(ev.ctrlKey, ev.altKey, ev.shiftKey); // When the event is triggered, whether the corresponding key is pressed true -- press false -- No
Event binding
binding
-
Element Event = function() {}
If you bind the same event to the same element, the following events will overwrite the previous ones
-
Event binding:
-
Standard: elements addEventListener('event type ', event handling function, capture or not);
Capture: false
-
ie: element attachEvent('on + event type ', event handling function);
function a() { console.log(1);}function b() { console.log(this);}// Click div to trigger a, B / / IE8 and the following: the object does not support the "addeventlistener" property or method console log(div.addEventListener); // ie8: undefined// div.addEventListener('click', a, false);// div.addEventListener('click', b, false);// If the current addeventlistener method exists, you can call if (div.addeventlistener) {div.addeventlistener ('click ', a, false); div.addeventlistener ('click', B, false);}// Standard: div.attachevent is not a functionconsole log(div.attachEvent); // Standard: undefined / / div.attachevent ('onclick ', a)// div.attachEvent('onclick', b);// Judge if (div.attachEvent) {/ / there is IE8 div.attachevent ('onclick ', a); div.attachevent ('onclick', b);}
-
encapsulation
function addEvent(ele, type, fn) { // Ele: element / / type: event type / / FN: bound event handler if (ele.addEventListener) {/ / standard ele. Addeventlistener (type, FN, false);} else { // ie8 ele.attachEvent('on' + type, fn); }}
Event mechanism difference
Standard:
\1. Event type without on
\2. Standard capture
\3. this points to the trigger source
\4. Positive sequence / sequential execution
ie:
\1. Event type plus on
\2. ie not captured
\3. this points to window
\4. Reverse order execution
Event cancellation
cancel
- Element Event element Event = null;
- Element addEventListener element removeEventListener('event type ', event handler, capture or not)
- Element attachEvent element detachEvent('on + event type ', event handling function)
// ie8: object does not support 'removeEventListener' property or method if (div.removeEventListener) {div.removeEventListener ('click ', a, false);}// Standard: div.detachevent is not a functionIf (div.detachevent) {div.detachevent ('onclick ', a);}
encapsulation
removeEvent(div, 'click', a);function removeEvent(ele, type, fn) { // Ele: element / / type: event type / / fn: event handler / / judge if (ele. Detachevent) {/ / IE8 ele. Detachevent ('on '+ type, fn);} Else {/ / standard ele.removeEventListener(type, fn, false);}}
Event flow
Event flow: when an event occurs, the fixed transmission process of events between parent and child nodes is event flow
Capture phase: events are passed layer by layer from window to child elements
Target determination stage: determine the event trigger target
Bubbling phase: the event source starts processing events. After processing, events will be passed from the child node to the parent node until the window
Each passing element will receive the current event and trigger the same type of event on itself
Event type:
Captured events (standard) bubbling events (default standard ie)
var divs = document.getElementsByTagName('div');function a(){ console.log(getComputedStyle(this).backgroundColor);}// Element Event bubbling event / / divs [0] onclick = a; // A is not followed by () / / divs [1] onclick = a; // A is not followed by () / / divs [2] onclick = a; // A is not followed by () / / divs [3] onclick = a; // A is not followed by () / / event binding for standard browsers / / divs [0] addEventListener('click', a, false); // Capture: true -- capture events; false -- bubble events / / divs [1] addEventListener('click', a, false); // Capture: true -- capture events; false -- bubble events / / divs [2] addEventListener('click', a, false); // Capture: true -- capture events; false -- bubble events / / divs [3] addEventListener('click', a, false); // Capture: true -- capture events; false -- bubble events / / divs [0] addEventListener('click', a, true); // Capture: true -- capture events; false -- bubble events / / divs [1] addEventListener('click', a, true); // Capture: true -- capture events; false -- bubble events / / divs [2] addEventListener('click', a, true); // Capture: true -- capture events; false -- bubble events / / divs [3] addEventListener('click', a, true); // Capture: true -- capture events; false -- bubble events
Stop bubbling
Problems caused by bubbling prevent bubbling from being solved
Event dependent object
Standard: EV stopPropagation();
ie: ev.cancelBubble = true;
One is the method and the other is the attribute. It is necessary to judge whether the method exists:
ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
If you don't want any event to bubble, stop it on the event of that element
// Click the button to display the div. / / 1 Get the element var BTN = document querySelector('button'); var div = document. querySelector('div'); console. log(btn, div);// 2. Add event BTN Onclick = function (EVS) {var EV = window.event | EVs; / / ev.stopPropagation(); / / IE8: the object does not support the "stopPropagation" attribute or method / / ev.cancelbubble = true; console.log (EV. stopPropagation); / / standard: function ie: undefined ev.stopPropagation? Ev.stopPropagation(): ev.cancelbubble = true; console.log (1) ; div.style. display = 'block';}// Add click event document. To the page onclick = function(){ div.style.display = 'none';}
Block default events
-
Element Event return false;
-
addEventListener ev.preventDefault();
-
attachEvent ev.returnValue = false;
-
Compatibility:
ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
-
Use constant scene:
-
Prevent bubbling:
If you do not want the child element to trigger the event of the parent element
-
Block default events:
Cancels the default behavior that comes with the browser
-
Both can occur at the same time
-
// document. oncontextmenu = function(){// return false;// }document. addEventListener('contextmenu', function(evs){ var ev = window.event || evs; // ev.preventDefault(); ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;});// document. Attachevent ('oncontextmenu ', function (EVS) {/ / var EV = window.event | EVs; / / / EV. Preventdefault(); / / IE8: the object does not support the "preventdefault" attribute or method / / / / ev.returnvalue = false; / / ev.preventdefault? Ev. Preventdefault(): ev.returnvalue = false; / /});
Keyboard events
Event type
onkeydown: when the key is pressed
onkeyup: when the key is lifted
onkeypress: when the key is pressed
document.onkeydown = function (evs) { // console.log(1); var ev = window.event || evs; // console.log(ev.key); // You can get the specific key ie: undefined / / console log(ev.keyCode); // The specific key codes are ASCII / / console log(ev.ctrlKey, ev.shiftKey, ev.altKey); // Whether the corresponding key is pressed true -- press false -- no. / / copy: ctrl + c outputs copy. / / if (ev.ctrl key = = true & & ev.keycode = = 67) {/ / console.log ('copy '); / /} console log(ev.keyCode);} document. onkeypress = function (evs) { var ev = window.event || evs; console.log(ev.keyCode, 'press');} document. onkeyup = function(){ console.log(2);}
The difference between down and press
- onkeydown: all keys are case insensitive encoding Shift + 1 = = > 49
- onkeypress: case sensitive corresponding case code for non special keys Shift + 1 = = > 33
Wheel event
roll
ie+chrome: element onmousewheel
ff: firefox
Event listener: DOMMouseScroll
// document. Onmousewheel = function() {/ / console.log ('rolled '); / /} / / if (document. Addeventlistener) {/ / document. Addeventlistener ('dommousescroll', function() {/ / console.log ('rolled '); / /}); / /} Function a() {console. Log ('roll away ');} document.onmousewheel = a;if(document.addEventListener){ document.addEventListener('DOMMouseScroll', a);}
Rolling direction judgment
- ie chrome: wheelDelta 120 150
On 120 / 150
- 120 / - 150
ff: undefined
- ff: detail 3
- 3 up
+ 3 lower
function a (evs){ var ev = window.event || evs; // console.log(ev.wheelDelta); // console.log(ev.detail); // I don't know whether it's up or down. Suppose var tag = 'up'// Determine whether wheeldelta exists if (ev.wheeldelta) {/ / IE Chrome / / console.log (ev.wheeldelta); / / if (ev.wheeldelta > 0) {/ / tag = 'up'; / /} else {/ / tag = 'down'; / /} tag = ev wheelDelta > 0 ? ' Up ':' down ';} Else {/ / FF / / console.log (EV. Detail); tag = ev. Detail > 0? 'down': 'up';} console.log(tag);}document.onmousewheel = a;if(document.addEventListener){ document.addEventListener('DOMMouseScroll', a);}
Event delegation
Event delegation: event agent, which gives the parent element what the child node wants to do
Principle: add the event originally added to the child element to the parent element. In the event, find the corresponding child node through target | srclelement, and the child node handles specific operations
Advantage: avoid using for, and subsequent added elements have the same event handling
Usage: if the child node has a unified event (each li adds a click event, and each li outputs an element)
ul.onclick = function(evs){ var ev = window.event || evs; // console.log(ev.target || ev.srcElement); var tar = ev.target || ev.srcElement; tar.style.background = 'red';}// Create node var Li = document createElement('li'); li. innerHTML = '12345';// Add in UL appendChild(li);
Callback function
When an action is completed, the function that needs to continue to be executed is the callback function
object-oriented
concept
Object oriented: a programming idea
Object oriented: focus on the result object
Process oriented: focus on every step of the process
Object oriented concept:
Use a template to create a series of objects, and use the methods and attributes in the objects to realize the current requirements
Object found object cannot be found to create object with object
Class: a template contains a series of actions or attributes in an object
es5 has no concept of class
The representational process can be abstracted into a property or method (abstraction) in an object
Instance: an object created through a template
features
-
Encapsulation: some parameters can reflect different effects according to different transmission data, and the use range of attributes and functions can be divided
-
Inheritance: accept common methods and properties from common functions or objects
-
Polymorphism: the results are different according to different parameters
+ number + number 'abc' + num splicing
Composition of objects:
-
Methods: dynamic sexual behavior
-
Attributes: static descriptive
create object
Literal
var variable name = {};
Disadvantages: only applicable to the creation of a single object
var obj = { name: 'Hu Ge', height: 188, tip: function(){ console.log('Handsome'); }}console.log(obj);
Instance creation
var variable name = new Object();
Disadvantages: code redundancy is not intuitive
// Create object var obj = new Object()// Add properties and methods obj Name = 'Hu Ge'; obj. height = 188; obj. Tip = function() {console. Log ('Very handsome ');} console.log(obj);
Factory mode
Disadvantages: unclear identification
var obj1 = createObj('Hu Ge', 188);var obj2 = createObj('Juen-Kai Wang', 187);console.log(obj1, obj2);console.log(typeof obj1);// Object instancof function name checks whether the object is created by the following function console log(obj1 instanceof createObj); // False -- not function createObj(name, height) {/ / create object var obj = new Object(); / / add attributes and methods obj.name = name; obj.height = height; obj.tip = function() {console. Log ('Very handsome ');}// Return object return obj;}
Object instancof function name checks whether the object is created by the following function
var arr = new Array();console.log(arr instanceof Array);// Object instancof function name checks whether the object is created by the following function console log(obj1 instanceof createObj); // False -- no
Constructor creation
process
-
Function names are capitalized (ordinary functions are distinguished)
-
Add methods and properties to this
-
Call with new, no new is no different from ordinary functions
new time
-
Create an empty object
-
Point this of the constructor to an empty object
-
Add properties and methods to this
-
Implicit return object
Disadvantages:
The same method will store many times in memory and waste memory
function CreateObj(name, height){ // Create object / / var obj = new object(); console. log(this); // Add properties and methods this name = name; this. height = height; this. Tip = function() {console. Log ('Very handsome ');}// Set the return value / / console log(obj); // return obj;}// Instantiated object var obj = new CreateObj('hu GE ', 188);console.log(obj);var obj1 = new CreateObj('cai Xukun ', 177);console.log(obj1);console.log(obj instanceof CreateObj); // true / / judge whether a method / function is the same in memory = = true -- it is the same false -- it is not the same console log(obj.tip == obj1.tip); // false
Prototype creation
prototype
Prototype object: on function
Prototype properties: the shared methods and properties at the top level of prototype (object) storage are inherited from the prototype object
By changing the methods and properties on the prototype object, the methods and properties can be shared with all objects created by the prototype
var arr = [1,2,3,5];var arr1 = [4,5,6,7,8];// push arr.push(9);arr1.push(9);console.log(arr, arr1);// Prototype: / / prototype object: function console Log (array. Prototype) / / prototype attribute: it refers to the top-level shared methods and attributes stored in the prototype (object) and the console inherited from the prototype object log(arr.__proto__); console. log(arr.__proto__ == Array.prototype); Array. prototype. Push = function() {console. Log ('zhao is preparing Chengdu for war again on his own ');} console.log(Array.prototype);arr.push(10);// By changing the methods and properties on the prototype object, the methods and properties can be shared with all objects created by the prototype
Prototype creation
Disadvantages of prototype creation: parameters cannot be transferred
// 1. Constructor function createobj() {}// 2. Add properties and methods to the prototype object (share all created objects) createobj prototype. Name = 'Hu Ge'; CreateObj. prototype. height = 188; CreateObj. prototype. Tip = function() {console. Log ('Very handsome ');}// 3. Instantiate object var obj = new CreateObj();console.log(obj);console.log(obj.name);obj.tip();var obj1 = new CreateObj();obj1.tip();console.log(obj1.name);console.log(obj.tip == obj1.tip); // true / / solve the problem of constructor / / disadvantage of prototype creation: cannot pass parameters
Blend creation
Mixed create constructor + prototype
// 1. Constructor (variable attribute method) function createobj (name, height) {this. Name = name; this. Height = height;}// 2. Add attributes and methods (invariant attributes and methods) to the prototype object createobj prototype. Tip = function() {console. Log ('Very handsome ');}// 3. Instantiate the object var obj = new CreateObj('hu GE ', 188);var obj1 = new CreateObj('cai Xukun ', 150);console.log(obj, obj1);obj.tip();obj1.tip();console.log(obj.tip == obj1.tip); // true
Dynamic blend creation
Judge whether the method or attribute to be added to the prototype exists. If it exists, it will not be added repeatedly. If it does not exist, it needs to be added
// 1. Constructor (variable attribute method) function createobj (name, height) {this. Name = name; this. Height = height; / / judge: judge whether the method or attribute to be added to the prototype exists. If it does not exist, add it repeatedly. If it does not exist, add console.log('calling object '+ this. Name); / / if (typeof (this. Tip) = =' function ') {/ / / / do not add / / console.log('Do not add '); / /} else {/ / console.log('add'); / / / 2. Add properties and methods (invariant properties and methods) to the prototype object / / createobj.prototype.tip = function() {/ / console.log('Very handsome '); / /} / / if (typeof (this. Tip)! =' Function ') {createobj. Prototype. Tip = function() {console.log('Very handsome');}}}}// 3. Instantiate object var obj = new CreateObj('hu GE ', 188);var obj1 = new CreateObj('cai Xukun ', 150);console.log(obj, obj1);obj.tip();obj1.tip();
Namespace
Namespace: divide the variables used in the page into objects of each block for storage
var page = { nav: {}, arr: [1,2,3,4]}page.nav.img = 'leftNav';page.nav.center = {};page.nav.center.baby = 'baby';page.nav.center.arr = ['SWAROVSKI', 'Trend four piece set', 'Fashion shoes'];console.log(page.nav.center.arr);console.log(page.arr);
Change this point
Function: change the direction of this
call: function call (new direction of this, parameter 1, parameter 2,..., parameter n);
apply: function Call (new direction of this, [parameter 1, parameter 2,..., parameter n]);
var obj = { 'name': 'Hu Ge', 'age': 38, 'sayname': function () { console.log(this.name); }, 'jishu': function (a, b) { console.log(this, a + b); }}var obj1 = { 'name': 'Zhang Sanfeng'}obj.sayname(); // Hu Ge obj sayname. call(obj1); // sayname: this-->obj1 this. Name -- > Zhang Sanfeng obj jishu(100, 200); obj. jishu. call(obj1, 500, 600); obj. jishu. apply(obj1, [50, 60]); obj. jishu. apply(1, [50, 60]); obj. jishu. apply(document.body, [50, 60]);
Object oriented inheritance
Inheritance:
Parent constructor (base class)
Subclass constructor (derived class)
classification
\1. Prototype chain inheritance
\2. Object pretends to inherit the subclass constructor, pretends to be the parent class, and exercises the permission of the parent class constructor
\3. Combinatorial inheritance
\4. Parasitic combinatorial inheritance
Prototype chain inheritance
// 1. Parent class constructor function student() {this. Tip = function() {console. Log ('good good study, day up, no game ');}} Student. prototype. Play = function() {console.log ('fairly OK ');}// 2. Subclass constructor function small (name, age) {this. Name = name; this. Age = age;}// 3. Prototype of subclass constructor = instantiated object of parent constructor small prototype = new Student();// 4. Instantiate the object var obj = new Small();console.log(obj);
Object impersonation inheritance
The object pretends to inherit this and points to the original parent constructor. This becomes an object created by the child constructor
// 1. Parent constructor function student (name, age) {this. Name = name; this. Age = age; this. Arr = [1, 2, 3, 4, 5]; this. Tip = function() {console. Log ('Study hard and make progress every day ')}} student prototype. play = function () { conosle.log('have fun');}// 2. Subclass constructor function small (name, age) {/ / 3. Call the parent constructor to change this to point to this console.log (this) of the current subclass constructor; / / student.call (this, name, age) created by small; this.game = function() {cosnole. Log ('canyon elite ');}} var obj = new Small('zhang San ', 18);var obj1 = new Small('zhang San 1', 18);console.log(obj);console.log(obj.a);console.log(obj.arr, obj1.arr);obj.arr.push(888);console.log(obj.arr, obj1.arr);// Disadvantages: methods and properties on the prototype object of the parent constructor cannot be inherited
Combinatorial inheritance
// Composition inheritance: prototype chain inheritance (invariant attribute method) + object impersonation inheritance (variable attribute method) / / 1 Parent constructor function student (name, age) {this. Name = name; this. Age = age; this. Arr = [1, 2, 3, 4, 5]; this. Tip = function() {console. Log ('Study hard and make progress every day ')}} student prototype. play = function () { conosle.log('have fun');}// 2. Subclass constructor function small (name, age) {/ / 3. Call the parent class constructor to change this to point to this student.call (this, name, age) that is the current subclass constructor; this.game = function() {cosnole. Log ('canyon elite ');}}// 4. Prototype object of subclass constructor = instantiation object of parent constructor small prototype = new Student(); Var obj = new small ('zhang San ', 18);var obj1 = new Small('zhang San 1', 18);console.log(obj);console.log(obj.a);console.log(obj.arr, obj1.arr);obj.arr.push(888);console.log(obj.arr, obj1.arr);console.log(obj.__proto__.constructor);
regular
concept
Regular: a regular string composed of characters with special meaning defined in advance
Regular: RegExp
Function: used to retrieve and replace strings
establish
Literal creation
var variable = / zifu / modifier;
var reg = /web/;console.log(reg);console.log(typeof reg); // objectconsole.log(reg.constructor);
Constructor
var variable = new RegExp('rule string ',' modifier ');
var reg1 = new RegExp('web', '');console.log(reg1);
Modifier
i: ignore case ignore case
g: global (entire string)
var reg = /web/ig;console.log(reg);console.log(typeof reg); // objectconsole.log(reg.constructor);var reg1 = new RegExp('web', 'g');console.log(reg1);
String method
-
split: string split('delimiter '/ regular);
var reg = /Web/;// var reg = /WWW/;// var reg = /\d/; // \d 0-9console.log(reg);// 13 split replace search matchvar STR = 'web123web123web456web'// Split: string split('delimiter '/ regular); console.log(str.split(reg));
-
replace: string replace('replaced character '/ regular, new character / function);
Replaced characters: only one character can be replaced at a time
Regular: replace all
console.log(str.replace(reg, '******'));
-
search(indexOf): string Search (regular); Return subscript - 1
console.log(str.search(reg));
-
match: string match (regular) returns the matched item
["web", "web", "web", "Web"]
["Web", index: 18, input: "web123web123web456Web", groups: undefined]
If no match is found, null is returned
console.log(str.match(reg));
Regular method
-
test
Verify whether the string has regular characters that meet the regular specification Test (string)
The returned result is true - yes, false - No
If g is not added, every match starts from 0
If g is added, each matching starts from the next bit of the result item from the previous matching. If the last one is found, false is returned, and the next one will start from 0
// Starting validation of subscript regexp lastIndex// 1. Verify that the string has regular characters that conform to the regular specification Test (string) / / the returned result is true --- yes, false --- no, var reg = /web/;console.log(reg.lastIndex); // 0console.log(reg.test(str)); // true// g: if G is not added globally, every match starts from 0 console log(reg.lastIndex); console. log(reg.test(str));// g: Add g, and each matching starts from the next bit of the result item from the previous matching. If the last one is found, it returns false, and the next time will start from 0. var reg = /web/g;console.log(reg.lastIndex); // 0console.log(reg.test(str)); // trueconsole.log(reg.lastIndex); // 3console.log(reg.test(str)); // trueconsole.log(reg.lastIndex); // 9console.log(reg.test(str)); // trueconsole.log(reg.lastIndex); // 15console.log(reg.test(str)); // falseconsole.log(reg.lastIndex); // 0console.log(reg.test(str)); // true
-
exec
exec: return array, item subscript string
Return matching results
Regular Exec (string);
["day", index: 17, input: "good good study, day day up", groups: undefined]
If g is not added, each match starts from 0. If g is added, each match starts from the next bit of the result item from the previous match. If the last is found, false is returned, and the next match will start from 0
var str = 'good good study, day day up';var reg = /day/;console.log(reg.lastIndex); // 0console.log(reg.exec(str));console.log(reg.lastIndex); // 0var reg = /day/g;console.log(reg.lastIndex); // 0console.log(reg.exec(str));console.log(reg.lastIndex); // 20console.log(reg.exec(str));console.log(reg.lastIndex); console.log(reg.exec(str)); // nullconsole.log(reg.lastIndex); // 0console.log(reg.exec(str));
Metacharacter
-
. any character other than line feed
var str = '\nabc';console.log(str);// var reg = /./;var reg = /.../;console.log(reg.exec(str)); // a
-
[]: character set, which writes any character in any character set you want to match
[^]: the character set does not match any character in the character set
[0-9] [a-z] [A-Z] [A-Za-z]
Any character does not need to be separated by (space, \ |) without quotation marks
var str = '0!/web123';// var reg = /[!/web]/;var reg = /[0-9a-zA-Z]/;console.log(reg.exec(str));var reg = /[^0-9a-zA-Z]/;console.log(reg.exec(str)); // !
-
\d: Match 0-9 \D: mismatch number
var str = 'web123';var reg1 = /\d/;console.log(reg1.exec(str)); // 1var reg2 = /\D/;console.log(reg2.exec(str)); // w
-
\w: Match numbers, letters_ \W: Mismatched numbers, letters_
var str = '_!123web';var reg = /\w/;console.log(reg.exec(str)); // _var reg = /\W/;console.log(reg.exec(str)); // !
-
\S: Match spaces \ S: match non spaces
var str = 'he is sleeping';var reg = /\s/;console.log(reg.exec(str)); // 2var reg = /\S/;console.log(reg.exec(str)); // h
-
\b: Match word boundaries \ B: match non word boundaries
A word has two boundaries, and a letter has two boundaries
var str = 'you are a beautiful girl';var reg = /\ba\b/; // Both sides of a are boundary spaces. Both sides of a match are boundary console log(reg.exec(str)); // 8var reg = /a\B/; // Match aconsole that is not a boundary on the right of A log(reg.exec(str)); // 4var reg = /\Ba\B/; // Match aconsole where neither the left nor the right of a is a boundary log(reg.exec(str));
-
^a: String starts with a and ends with a $: the entire string ends with a
var str = 'today is a fun day';// var reg = /^a/; // String starting with a var reg = /^t/;console.log(reg.exec(str));// var reg = /a$/; // A terminated string var reg = /y $/// Y-terminated string console log(reg.exec(str));
classifier
-
a?: Indicates that 1 or 0 a matches the first character from left to right
var str = 'web123';var str = '1web123';var reg = /\d?/;console.log(reg.exec(str));
-
A *: it means that 0 or consecutive a matches the first character from left to right. If it matches, match as many as possible
var str = 'web123456';var str = '123456web345';var reg = /\d*/;console.log(reg.exec(str));
-
a +: it means to match as many as possible
var str = 'web1234567';var reg = /\d+/;console.log(reg.exec(str));
-
a{n,m}: match at least N times and at most m times
a{n}: match only n times
a{n,}: match at least N times
Note: do not add spaces
Match as many as possible
var str = 'web1234567890123456';var reg = /\d{3,7}/;console.log(reg.exec(str));var reg = /\d{6}/;console.log(reg.exec(str));var reg = /\d{1,}/;console.log(reg.exec(str));
special
-
|: or a|b matches a or B
var str = 'web0123webabc'; var reg = /web1|weba/;console.log(reg.exec(str));
-
(): grouping indicates matching an item in parentheses
() priority calculation
var reg = /web(\d|a)/; // Match the web splicing character (web1 weba) var reg = / Web (\ d|a) (\ d|b) /// Match web 1 weba (WEB + number weba) followed by a number or bconsole log(reg.exec(str));// $ 1 $2 is the result of the final matching character in the regular () console log(RegExp.$1); // Indicates to get the matching result 0console. In the first parenthesis log(RegExp.$2); //
-
(?!..): Cannot be a regular in the preceding parenthesis
// Set password: combination of letters and numbers, 6-18 digits, var str = 'abc1234456'// Cannot be a pure number ^ \ d{6,18}$// var str = '123456789'// Cannot be a pure letter. Write the regular of pure letter first / / var regs = / ^ [a-za-z] {6,18} $/// var str = '123456789a'; var str = 'qwertyuiop1'; var reg = /(?!^[a-zA-Z]{6,18}$)(?!^\d{6,18}$)^[0-9A-Za-z]{6,18}$/; console. log(reg.exec(str));
Anonymous function
Function classification
-
Ordinary function
function fn(){ console.log(1);}fn();
-
Expression function
var fn1 = function(){ console.log(2);}fn1();
-
Constructor
function Fn(){ this.name = 'Zhang San';}console.log(new Fn());
-
Event handler
document.onclick = function(){ alert(1);}function a(){ alert(2);}document.onclick = a;
-
Anonymous function
// function (){// console.log(4);// }
Execute function now
concept
An error reporting function without a name adds () to it to convert the error reporting part into an expression
Calling function of function ()
advantage:
-
When the function is executed only once, enter the page and the event is triggered
-
Just joined the new team to develop js code to ensure that the complete page of js will not occupy the function name
-
graceful
// An error reporting function without a name adds () to it and converts the error reporting part into an expression (function() {console. Log (1);})// Function () (function () {console. Log (1);}) (); (function () { console.log(2);} ());
characteristic
-
Anonymous functions have formal parameters and arguments
Formal parameter: after function ()
Argument: called ()
(function (a, b) { console.log(a, b);})(10, 20);
-
There is a return value
Set return value: return value;
Receive return value: var variable = function ();
var s = (function (a, b) { return a + b;})(10, 20);console.log(s);
closure
concept
Closures: functions that can read internal variables of other functions, nested functions in functions, and internal functions access variables of external functions.
Essentially, a bridge connecting the inside and outside of a function.
Features: variables in closures are similar to global variables. They will always be stored in memory and will not be destroyed
Problem solved: the problem of global i in the for loop simulates private variables
function a(){ // External var s = 10; Return function b() {/ / internal s + +; console.log (s);}} var mn = a(); console. log(mn); // Function bmn()// 11 s++; log(s); mn(); // twelve
effect
Solve global i
// Click each Li to output the subscript / / because the execution speed of for is very fast. For a moment, VAR LIS = document getElementsByTagName('li'); console. log(lis); For (VaR, I = 0; I < LIS. Length; I + +) {/ / console.log (I); / / 1. Anonymous function / / 2. Pass global I as an argument to an anonymous function (function (s) {/ / formal parameter only works in its local scope console.log (s); LIS [S]. Onclick = function() {console.log (s);}}) (i); // lis[i]. onclick = function(){ // console.log(i); // 10 // }}
Analog private variable
// 1. An empty function receives data. Function fn (value) {this. Value = value; VAR that = this; / / a specific method is required to modify this. Fun = {'setValue': function (V) {console. Log (this); that. Value = V;}, ' getValue': function(){ console.log(that.value); } }} Var obj = new FN ('hu GE '); console.log(obj);obj.fun.setValue('wu Yifan '); console.log(obj);obj.fun.getValue();// Normal function fn(v) {/ / external function VaR value = V; return {'setValue': function (V) {/ / internal function value = V;}, ' GetValue ': function() {/ / internal function console.log (value);}}} Var obj1 = FN ('hu GE ')// A man named Hu Ge console was born log(obj1); // Object obj1 getValue(); obj1. SetValue ('zhang San ')// Renamed Zhang San obj1 getValue(); // Zhang San var obj2 = fn('zhang San ')// Another man named Zhang San was born getValue(); // Zhang San console log(obj1 == obj2); // false
AJAX
concept
ajax: it is a technology to quickly create dynamic interactive web pages
Update some data without refreshing the full page
ajax: Asynchronous Javascript and xml
Asynchronous javascript and xml
Through a small amount of data interaction with the background server, the page is updated
For: dynamic requests to access data
Shopping cart news refresh hotspot update full page data
request
- Asynchronous: you do not need to wait for the data returned by the current request before executing the subsequent code
- Synchronization: you must wait for the request to return data before executing subsequent codes
Error message
Access to XMLHttpRequest at 'file:///E:/1026/day15/a.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https. Check how the file is opened: ajax requests the server to open vscode: Live Sever
readyState
0: ajax object created
1: link established
2: request sent
3: the background received the request
4: the background starts to process the request, and the response package is returned after processing
status
1XX: Information
2XX: request succeeded 200
3XX: redirect 304
4XX: page error 400 404 403 401 405
5XX: server error 500 501 504
get
- Creating ajax objects
- Establish a connection ajax object open('request method ',' request address' +? + 'parameter', asynchronous or not)
- Send request
- Status of listening request
- Listen for requests completed by background processing
- get data
// 1. Create Ajax object var ajax = new XMLHttpRequest();console.log(ajax);// 2. Establish connection Ajax object Open ('request method ',' request address' +? + 'parameter', asynchronous or not) / / request method: get post / / request address: local address online interface / / asynchronous or not: true --- asynchronous or false --- synchronous / / parameters: key = value & & key = valueajax open('get', './a.txt?a=1&b=2', true); console. log(ajax);// 3. Send request Ajax send(); console. log(ajax);// 4. Listen for the request status. / / the request status change event Ajax Onreadystatechange = function() {console.log (Ajax. ReadyState); / / Ajax request status / / 5. Listen for requests completed by background processing if (Ajax. ReadyState = = 4 & & Ajax. Status = = 200) {/ / 6. Get data console.log(ajax.response);}}
post
- Creating ajax objects
- Establish connection: open('request method ', request address, asynchronous or not)
- Set request header
- Send request (request parameter);
- Status change of listening request
- Listening request status and return value
// 1. Create Ajax object var Ajax = new xmlhttprequest()// 2. Establish connection: open ('request method ', request address, asynchronous or not) Ajax open('post', 'a.txt', true);// 3. Set request header Ajax setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8;');// 4. Send request (request parameter); ajax. send('a=1&&b=2');// 5. Listen for the status change of the request Ajax Onreadystatechange = function() {/ / 6. Listen for request status if (Ajax. ReadyState = = 4 & & Ajax. Status = = 200) {console.log (Ajax. Response);}}/* Content type: application / x-www-form-urlencoded: default form text/plain: text mulitipart / form data: file vscode does not support post request 405 wampsever*/
encapsulation
function ajax(type, url, data, fn) { // Type: request method / / url: request address / / data: request data / / FN: callback function after the request succeeds / / 1 Create Ajax object var Ajax = new xmlhttprequest(); If (type = ='post ') {/ / 2. Establish a connection: open('request method', request address, asynchronous or not) ajax.open (type, url, true); / / 3. Set the request header ajax.setrequestheader ('content type ',' application / x-www-form-urlencoded; charset = UTF-8; '; / / 4. Send the request (request parameter); ajax.send (data);} Else {Ajax. Open (type, url + '?' + data, true); / / 3. Send request Ajax. send();}// 5. Listen for the status change of the request Ajax Onreadystatechange = function() {/ / 6. Listen for request status if (Ajax. ReadyState = = 4 & & Ajax. Status = = 200) {/ / console.log (Ajax. Response) ; // You can't get the result by setting the return value. / / return Ajax response; // Wait for the data returned from the background before outputting the result. Callback function / / pass the data returned from the request as an argument to the callback function fn(ajax.response);}}}
artTemplate
step
\1. layout
\2. Comment page
\3. Import public library ujiuye art template
\4. Get parent node
\5. New template template: the template is written in front of its own js and assigned with id
\6. Load template template to page
var variable = template('template id ', data);
\7. Request data
\8. Add the generated html fragment to the parent element
grammar
Get the attribute value of the object in template:
{{property name}}
Circular statement
{{each data as value I (subscript)}}
Page render clip
{{/each}}
<script type="text/html" id="oul"> {{onlineSell}} {{each onlineSell value i}} Each value: {{value}} Each subscript: {{i}} <br> <li><img src="{{value.img}}" alt=""></li> {{/each}}</script><script> var ul = document.querySelector('ul'); console.log(ul); ajax('get', './ujiuye/data/lessonContent.json', '', function (res) { // console.log(res); var r = JSON.parse(res); console.log(r); // 6. Load the template var template = template ('oul ', r.goodlesson); console. log(temp); // 7. Render data UL innerHTML = temp; });</ script>
localStorage
localStorage: cache data json data
storage
- localStorage. Attribute name = value; Only one data can be stored at a time
- localStorage.obj = obj; // [object Object]
- Note: localStorage can only store strings
- Convert js data to string JSON stringify
// Localstorage: cache data json data console log(localStorage); // Stored data: 1 localStorage. Attribute name = value; Only one data can be stored at a time localstorage Name = 'Peng Yuyan'; localStorage.age = 30;// 2. localStorage.setItem('attribute name ',' attribute value '); localStorage. height = 180; Var obj = {'name': 'Zhang San', age: 88}// localStorage. obj = obj; // [object] / / localstorage can only store strings. / / convert js data into string json stringifyvar tt = json. stringify(obj); console. log(typeof tt);
eliminate
Caches stored locally are not automatically purged and do not expire
It can only be cleared manually
// You can only manually clear localstorage obj = '';// Remove local cache localstorage removeItem('obj');// Empty local cache empty all data localstorage clear(); console. log(localStorage);
audio
Available properties:
src: imported address
controls: controller
muted: Mute
Autoplay: autoplay
Loop: loop
console.log(audio.src); // Absolute address console log(audio.controls); // Whether the controller displays true -- displays false -- console is not displayed log(audio.muted); // Mute true -- mute false -- unmute console log(audio.autoplay); // Whether to set autoplay true -- set false -- console is not set log(audio.loop); // Whether to set loop playback true --- set false --- console is not set log(audio.duration); // Music duration; When the music is loaded, the console is in seconds log(audio.currentTime); // Current playback time console log(audio.currentSrc); // Current playback address console log(audio.paused); // Pause true --- pause false --- the console is not paused log(audio.ended); // Whether the end position is true -- the playback is finished, false -- the console is not completed log(audio.volume); // Volume 0 --- 1audio volume = 0;// You can play the event audio oncanplay = function(){ console.log(audio.duration); console.log(audio.currentSrc);}// Play time change event audio ontimeupdate = function(){ // console.log(audio.currentTime); // console.log(audio.paused); console.log(audio.ended);}// 1. End audio onended = function(){ console.log(111);}// 2. Pause audio onpause = function(){ console.log(222);}// Get button var BTNs = document getElementsByTagName('button');// Click the first button to mute BTNs [0] onclick = function(){ audio.muted = !audio.muted;}// Click the second button to automatically play BTNs [1] onclick = function(){ audio.autoplay = true; console.log(audio.autoplay);}// Click the third button to cycle BTNs [2] onclick = function(){ audio.loop = true; console.log(audio.loop);}// Click set volume 0 --- 1, including 0,1btns [3] Onclick = function() {/ / get the current volume audio.volume = (audio. Volume * 100 + 10) / 100; console.log(audio.volume);}// Click music to start playing BTNs [4] onclick = function(){ audio.play();}// Click pause BTNs [5] onclick = function(){ audio.pause();}// Click to switch to half and start playing BTNs [6] Onclick = function() {/ / find the total duration console.log (audio.duration / 2); audio.currenttime = audio.duration / 2;}// Click to switch the address BTNs [7] Onclick = function() {audio. SRC = '. / Chen Jieli Lu Shuang Zu Qing Wang Wei crazy Guobao. mp3'; / / relative address}
video
video: video
src: Address
width/height: width/height
poster: video playback page picture
controls: controller
muted: Mute
Autoplay: autoplay
Loop: loop playback
/* 1. Get element*/var video = document.getElementsByTagName('video')[0];console.log(video);// The obtainable property can also be set to console log(video.src); console. log(video.currentSrc); // The console can only be obtained when playing log(video.controls); // Whether to display the controller console log(video.muted); // Mute console log(video.width, video.height); console. log(video.loop); // Whether to cycle the console log(video.poster); console. log(video.paused); // Whether to play console log(video.ended); // End console log(video.volume); // Volume console log(video.playbackRate); // Double speed [0 -- 2] console log(video.currentTime); // Current playback time console log(video.duration); // Total playback time / / update video ontimeupdate = function () { // console.log(video.currentSrc); if (video.muted) { video.muted = false; } // console. log(video.paused); // Play / / console log(video.ended); // console. log(video.currentTime); // console.log(video.duration);}// You can play video oncanplay = function () { // console.log(video.currentSrc);} var btns = document. getElementsByTagName('button'); btns[0]. onclick = function(){ video.playbackRate = 0.1;} btns[1]. onclick = function(){ video.playbackRate = 1;} btns[2]. onclick = function(){ video.playbackRate = 2;}// Playback speed change event video Onratechange = function() {console. Log (111); video. Load(); / / reload video.play();}btns[3].onclick = function(){ video.pause();}// Event triggered when pausing video onpause = function(){ console.log(123);}// Event triggered at the end of playback video Onended = function() {console.log ('finished ');} btns[4].onclick = function(){ video.currentTime = video.duration / 2; video.play();}
Mobile terminal
Introduction to mobile terminal
-
pc side events are available, but not recommended
-
Because the simulator is good and bad, in order to avoid elements The on event mode may be insufficient. Use addEventListener to add it
Event classification
-
The event triggered when the finger is pressed: touchstart
-
The event triggered when the finger is raised: touchend
-
The event triggered when the finger moves: touchmove as long as the finger presses in the element, the full screen can be displayed again
var div = document.getElementsByTagName('div')[0];// div.onclick = function(){// console.log(1);// }// div.addEventListener('click', function(){// console.log(2);// });div.addEventListener('touchstart', function(){ console.log(3);});div.addEventListener('touchend', function(){ console.log(4);});div.addEventListener('touchmove', function(){ console.log(5);});
Mobile terminal problem
-
In order to monitor whether the user double clicks or clicks, the event on the pc side has a delay of 300ms
var div = document.getElementsByTagName('div')[0];// div.onclick = function(){// console.log(1);// }div.addEventListener('click', function(){ console.log(2);});div.addEventListener('touchstart', function(){ console.log(3);});
-
In the mobile terminal, if the click event is triggered by the upper element within 300ms, the lower element itself also exists. If the upper element is hidden, the event will drift to the lower element
var div = document.getElementsByTagName('div')[0];// div.onclick = function(){// console.log(1);// }// div.addEventListener('click', function(){// console.log(2);// });div.addEventListener('touchstart', function(){ console.log(3); div.style.display = 'none';});
Properties of the event object
var div = document.getElementsByTagName('div')[0];div.addEventListener('touchstart', function(evs){ var ev = window.event || evs; console.log(ev); // console.log(ev.touches); // List of all fingers on the current screen / / console log(ev.targetTouches); // List of all fingers on the current trigger element / / console log(ev.changedTouches); // List of fingers that triggered the event / / each finger is another object var touch = ev changedTouches[0]; console. log(touch); console. log(touch.identifier); // Finger ID console log(touch.target); // Trigger source console log(touch.screenX, touch.screenY); // The distance from the upper left corner of the screen when the finger is pressed 74 212 console log(touch.clientX, touch.clientY); // The distance from the upper left corner of the visual area of the screen when the finger is pressed log(touch.pageX, touch.pageY); // The distance from the top left corner of the page when the finger is pressed log(touch.rotationAngle); // Rotate the distance console log(touch.force); // Finger press pressure console log(touch.radiusX, touch.radiusY); // Finger radius});
touch
introduce
touch.js: Baidu cloud
Download: https://www.bootcdn.cn/touchjs/
Designed for mobile terminals, ie8 webkit
Compressed version: touch Min.js smaller working capacity
Uncompressed version: touch JS format clear learning
touch.on
-
Add events to elements
touch.on('selector ',' event ', callback function)
Selectors: selectors in all css #id Class tagName, parent > child
Events: multiple events can be written, separated by spaces
Callback function: the function executed when the event is triggered
touch.on('div', 'tap doubletap hold', function(ev){ console.log(1);});
-
Event delegation
touch.on('parent selector ',' event ',' child selector ', callback function)
touch.on('div', 'tap', 'p,li', function(){ console.log(this);});
Event object properties
touch.on('div', 'tap swipe', 'p,li', function(ev){ ev.startRotate(); // Start rotating the console log(ev); // Customevent event object / / console log(ev.originEvent); // Native event object / / console log(ev.type); // Event type / / console log(ev.target, ev.srcElement); // Trigger source / / console log(ev.position); // Mouse position / / console log(ev.direction); // Sliding direction / / console log(ev.distanceX, ev.distanceY); // Sliding distance / / console log(ev.rotation); // Rotation angle / / console log(ev.fingersCount); // Number of fingers / / console log(ev.distance); // Moving distance console log(ev.duration); // Duration touchstart to touchend});
Event classification
Click: tap
Double click: doubletap
Long press: hold
slide:
swipe
swiping
swipestart
swipeend
swipeleft
swiperight
swipeup
swipedown
Drag class:
drag
dragstart
dragend
Rotation class:
rotate
rotateleft
rotateright
// touch. on('div', 'tap doubletap hold swipe swiping swipestart swipeend swipeleft swiperight swipeup swipedown drag dragstart dragend rotate rotateleft rotateright', function(ev){// console.log(ev.type);// // console.log(ev.x, ev.y);// }); touch. On ('img','touchstart', function (EV) {/ / console.log (ev.type); ev.startRotate (); / / want to trigger the rotation event, monitor the start of the finger event in which to call startRotate / / console.log (ev.x, ev.y);}; touch. on('img', 'rotate rotateleft rotateright', function(ev){ console.log(ev.type); // console.log(ev.x, ev.y);});
JQuery
Basic introduction
-
Introduction: jQuery is an efficient, concise and feature rich JavaScript tool library. Its API is easy to use and compatible with many browsers, which makes it easier to traverse and manipulate HTML documents, event processing, animation and Ajax operations
-
Philosophy: write less, do more
-
Baidu download address:
cdn: https://www.bootcdn.cn/jquery/
Official website: https://jquery.com/
-
Version used:
jquery.js: uncompressed version learning
jquery.min.js: compressed version working
-
Introduction method:
\1. Import local files: common
\2. Import cdn file: not commonly used
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> --><script src="js/jquery.js"></script>
-
Latest version:
3.5.1
2XX and 3xx are not compatible with IE678
1XX compatible with IE678
-
advantage:
\1. Write less and do more
\2. Powerful selector
\3. Lightweight
\4. DOM document
\5. animation
\6. Implicit iteration
\7. Chain operation
\8. ajax operation
\9. Open source free source code release
\10. … other
-
file:
https://jquery.cuishifeng.cn/
$relationship with jQuery
$and jQuery are the same thing
console.log(jQuery);console.log(window.jQuery);console.log(window.$);console.log($);console.log(window.jQuery == $);
Wait for the page to load
window.onload only one page can be written. If more than one page is written, the following will overwrite the previous execution time (waiting for pages and resources)
ready one page can write multiple superimposed execution, and the execution time can be shortened (after the DOM structure is loaded)
// 1. The native waiting page and resources are loaded into the window onload = function(){ console.log(1);} window. onload = function(){ console.log(2);}// 2. JQuery waits for the page to load / / 2.1 $(document) ready(function(){})$(document). ready(function(){ console.log(3);});// 2.2 $(). Ready (function)$ (). ready(function(){ console.log(4);});// 2.3 $(function(){});$(function(){ console.log(5);});
Mutual transformation of jquery object and js object
-
js object to jq object
js to jq object $(js object)
window.onload = function(){ // 1. Get the element var Li = document getElementsByTagName('li'); console. log(li); // Htmlcollection / / elements obtained through the native method of obtaining elements can use the methods in js / / js is converted to jq object $(js object) console log($(li)); // jQuery. fn. init console. log($(li[0])); // jQuery. fn. init}
-
Convert jQuery object to js object
- jq object [subscript]
- jq object Get (subscript)
$(function(){ var li = $('li'); // $('selector') console log(li); // jQuery. fn. Init / / the element obtained through the jq method is called a jQuery object. You can use the jq method / / convert the jQuery object into a js object. jq object [subscript] console log(li[0]); // < Li > 0001 < / Li > the specific tag is also the js object console log(li.get(0)); // jq object Get (subscript) the js object represented by the specific subscript});
selector
Basic selector
console.log($('li')); // Label selector console log($('.a')); // Class name selector console log($('#five')); // ID name selector console log($('.a,#five')); // Basic selector
Level selector
// jq element CSS ('attribute name ',' attribute value ') / / jq does not report an error unless there is a syntax error. / / the js object uses the jq method, and some required parameters are written incorrectly in console log($('ul li'). css('background', 'red')); console. log($('ul > li'). css('background', 'yellow')); console. log($('.box + div'). css('background', 'blue')); console. log($('.box ~ div'). css('background-color', 'green'));
Filter selector
Basic filter selector
$('ul li:first').css('background', 'red'); // First element $('ul li: last ') css('background', 'red'); // The last element is $('ul li: not (. Box ') css('background', 'green'); // Element $('ul li: even ') of li whose class name is not box css('background', 'red'); // Element $('ul li: odd ') with even index li css('background', 'blue'); // Element $('ul li: EQ (5) 'of li with odd index css('background', 'yellow'); // Gets the element $('ul li: LT (5) 'with index 5 css('background', 'pink'); // Elements with index less than 5 $('ul li: GT (5 ') css('background', 'skyblue'); // Elements with index greater than 5
Content filter selector
$('li:contains(6)').css('background', 'red'); // The text contains $('li: has (span) 'of a text css('background', 'blue'); // There is span $('li: parent ') in the tag css('background', 'orange'); // There is a text label $('li: empty ') in Li css('background', 'blue'); // Li is empty
Visibility filter selector
// Invisible: input type = "hidden" display: noneconsole log($('li:visible')); console. log($('li:hidden')); console. log($('body *:hidden')); console. log($('body *:visible'));
Attribute filter selector
$('li[tag]').css('background', 'red'); // Get Li $('li [tag = 123] ') with tag attribute css('background', 'green'); // Li $('li [tag! = 123] ') with tag attribute value of 123 css('background', 'blue'); // Li $('li [Title ^ = a] ') with tag attribute value not 123 css('background', 'yellow'); // Title Attribute starts with a $('li [Title $= a] ') css('background', 'orange'); // Title Attribute ends with a $('li [Title * = a] ') css('background', 'skyblue'); // There is a character in the title
Child element filter selector
$('ul li:nth-child(1)').css('background', 'red'); // Nth child select the first few $('ul: nth child (1 ') css('background', 'blue'); // Nth child select the first few $('ul: nth child (event ') css('background', 'pink'); // Nth child selects even $('ul: nth child (odd) ' css('background', 'orange'); // Nth child select odd $('ul: nth child (3N + 1) ' css('background', 'blue'); // Expression 1 3 7 $('ul: first child ') css('background', 'purple');$ ('ul :last-child'). css('background', 'purple');
Form property filter selector
console.log($('input:enabled')); // Get the available input box console log($('input:disabled')); // Get the unavailable input box console log($(':checkbox:checked')); // Gets the selected checkbox console log($(':radio:checked')); // Gets the selected radio box console log($('select :selected')); // Gets the item of the selected drop-down list
Form element filter selector
console.log($(':input')); // Get all forms console log($(':text')); // Get all input boxes console log($(':radio')); // Radio button console log($(':checkbox')); // Check button console log($(':button')); // Button console log($(':reset')); // Reset button console log($(':submit')); // Reset button console log($(':image')); // Upload picture console log($(':file')); // Upload file
Node traversal
Child node
// All the following methods can accept a selector as a filter condition. / / 1 Child node console log($('ul'). children()); console. log($('ul'). children('li')); console. log($('ul'). children('li:odd'));// 2. Previous sibling node $('. Box') prev(). css('background', 'red'); // Get previous $('. Box') prevAll(). css('background', 'blue'); // Get all previous $('. Box') prevAll('a'). css('background', 'black'); // Get all the previous / / 3 Next sibling node $('. Box') next(). css('background', 'orange'); // Get the next $('. Box') nextAll(). css('background', 'green'); // Get all the following / / 4 Get all sibling nodes $('. Box') siblings(). css('background', 'pink'); // Get all sibling nodes
Parent node
// Get the parent node console log($('.box'). parent()); // Direct parent node console log($('.box'). parents()); // Get all parent nodes htmlconsole log($('.box'). parents('ul')); // You can receive the selector as a receive condition
filter
// Filter node: find filter not $('ul ') find('.box'). css('background', 'pink'); // Find UL and then find the element $('li ') with the class name box in UL filter('.box'). css('background', 'orange'); // Find Li and filter out the class name in Li Box element $('li ') not('.box'). css('background', 'blue'); // Find Li and filter out no class name in Li Box element
Take assignment
Integration of fetching and assignment: the same method is used for fetching and setting values
Value: only get the value of the first element that meets the selector conditions
Assignment: traversal assignment (implicit iteration)
Operation properties
attr
jq object attr('attribute name ') get
jq object The attr (attribute name, attribute value) setting is only applicable to the setting of a single attribute
jq object attr({
'attribute name': attribute value,
'attribute name 1': attribute value 1,
}); It is suitable for batch setting multiple attributes
You can manipulate both intrinsic and custom attributes
jq object removeAttr('attribute name ');
console.log($('.box').attr('class'));console.log($('.box').attr('id'));console.log($('.box').attr('tag'));$('.box').attr('id', 'a45678');$('.box').attr('tag', 'weekDay');$('li').attr({ 'name': 'isLi', 'age': 20});$('li').attr('name', '');$('li').removeAttr('name');
prop
The syntax is exactly the same as that of attr, and the use is limited
\1. When only adding attribute names works (inherent attributes)
\2. The attribute values are only true, false checked and disabled selected
jq object prop('attribute name ') get
jq object prop('attribute name', 'attribute value') setting is only applicable to the setting of a single attribute
jq object prop({
'attribute name': attribute value,
'attribute name 1': attribute value 1,
}); It is suitable for batch setting multiple attributes
You can manipulate inherent attributes
jq object removeProp('attribute name ');
console.log($(':checkbox'));console.log($(':checkbox').prop('checked'));// $(':checkbox'). prop('checked', true);$ (':checkbox'). Prop ({'name': 'check', 'value': 'check box', 'tag': '123' / / 'checked': true})// console. log($(':checkbox'). removeProp('checked'));$ (':checkbox'). attr('checked', true);$ (':checkbox'). attr('checked', false);
call chaining
Chain calling principle: after being called, the jq method returns the object operated by the current method or the object after the operation
Operation class name
addClass
Add a class name jq object addClass('class name 1, class name 2 ')
// $('div').addClass('active');// $('div').addClass('active bg');// console.log($('div').addClass('active').addClass('bg'));
removeClass
Remove class name: jq object removeClass('class name 1 ')
// $('div').removeClass('active bg');
toggleClass
Add or remove class name jq objects toggleClass('class name ')
If there is a class name, remove it. If there is no class name, add it
$('div').toggleClass('active');
hasClass
Whether there is a class name: jq object hasClass('class name ')
If yes, return true. If no, return false
console.log($('div').hasClass('active'));
is
Has a selector or state: jq object is('. Class name') () is a selector
If yes, return true. If no, return false
console.log($('div').is('.active'));
Operation style
-
jq object css('attribute name ') gets the corresponding value
-
jq object css('attribute name', 'attribute value') setting only sets a single style attribute
-
jq object css({'attribute name': attribute value, 'attribute name 1': attribute value 1}) setting
be careful:
Attribute name: it can be quoted or not. If not, it needs to be converted to hump naming method. If not, it is recommended to quote
Attribute value:
With unit '30px'
The value 300 adds px by default
Expression '+ = 40' - = * =/=
console.log($('div').css('width'));console.log($('div').css('width', 300));console.log($('div').css({ 'width': 500, 'height': '300px', // fontSize: 30 // 'font-size': 30 'font-size': '+=20'}));$('button').click(function(){ $('div').css({ 'font-size': '+=10', });})
Operation content
text
text(): similar to innerText
\1. Value: jq object text(); Get the contents of all qualified elements
\2. Settings: jq objects text('content '); The following will override the previous traversal settings
console.log($('div').text());// $('div').text('This is my new content ');
html
html(): similar to innerHTML
\1. Value: jq object html(); Gets the content of the first of the eligible elements
\2. Settings: jq objects html('content '); The following will override the previous traversal settings
Can identify labels
console.log($('div').html());console.log($('div').html('<i>This is my new content</i>'));$('p').text('<i>This is my new content</i>');
val
val(): similar to value
\1. Value: jq object val(); Gets the content of the first of the eligible elements
\2. Settings: jq objects val('content '); The following will override the previous traversal settings
console.log($('input').val());$(':text').val('New content');console.log($(':radio:checked').val());$(':radio').val(['male']); // Value console on value log($(':checkbox'). val());$ (':checkbox'). val(['LOL', 'CS']); console. log($('#city'). val());$ ('#city'). val('nj');// $ ('#city'). val('nj '); console. log($('#mul'). val()); console. log($('#mul'). val(['bj', 'nj']));
BOM
Three width and height
-
width height
-
Visual: clientWidth
-
Occupation: offsetWidth
-
Roll height: scrollTop
console.log($('div').width(), $('div').height()); // Width and height content console log($('div'). innerWidth(), $('div'). innerHeight()); // Visual width visual height content + paddingconsole log($('div'). outerWidth(), $('div'). outerHeight()); // Space width and height content + padding + border / / there is a Boolean value of the parameter: true -- content + padding + border + margin false / not passed -- content + padding + borderconsole log($('div'). outerWidth(true), $('div'). outerHeight(true));// Get the jq object Width (numeric) $('div ') width(500);// jq object Innerwidth (numeric) padding does not change and becomes the specific content width and height $('div ') innerWidth(500); // Content + padding = 500 / / jq object Outerwidth (numeric value, whether margin is included or not) true -- indicates that false is included / not passed -- indicates that $('div ') is not included outerWidth(500); // content + padding + border = 500 $('div'). outerWidth(500, true); // content + padding + border + margin = 500
Element location
The distance from the current element to the parent element with the positioning attribute
console.log($('div').offset());console.log($('div').offset().top);
Rolling height
$(window).scroll(function(){ console.log($(this).scrollTop()) console.log($(this).scrollLeft())});
DOM
Create node
$('html fragment')
var li = $('<li>This is a new label</i>');console.log(li);
Append node
/* 1. Append to the end of the parent node*/// $('ul').append(li); // Parent node Append (child node) / / Li appendTo('ul'); // Child nodes Appendto ('parent node selector ') / / if it is a one-time batch, add it to the parent element / / Li appendTo('ul:eq(0)');// li.appendTo('ul:eq(1)');// Adding the same node to different parent nodes in separate steps will cause physical displacement / * 2 Append to the beginning of the parent node prepend prependto * / / $('ul ') prepend( li); // Parent node Prepend (child node) / / Li prependTo('ul'); // Child nodes Prependto (parent node) / * 3 Insert before * / / $('. Box') before appending a reference element before( li); // Reference node Before (new node) / / Li insertBefore('.box'); // New node insetBefore('selector ') / * 4 Append to a reference element after insetafter * / / $('. Box') after( li); // Reference node After Li insertAfter('.box'); // New node Insertafter ('selector ')
Delete node
-
detach: delete the current element, return the deleted element, and retain the behavior of the previous element
-
remove: delete the current element and return the deleted element. The behavior of the previous element cannot be retained
-
Empty: empty the current element (delete all child elements of the current element)
$('ul li').click(function(){ $(this).css('background', 'red');});// : EQ (0) jq object EQ (subscript) gets the jq object $('button: EQ (0 ') click(function(){ var li = $('ul li').eq(0).detach(); console.log(li); setTimeout(function(){ $('ul').append(li); }, 2000);});$ ('button:eq(1)'). click(function(){ var li = $('ul li').eq(0).remove(); console.log(li); setTimeout(function(){ $('ul').append(li); }, 2000);});$ ('button:eq(2)'). click(function(){ $('ul').empty();});
Clone node
jq object Clone (Boolean value) returns that the cloned node page does not exist and needs to be appended to the page
Do not pass / false indicates no cloning behavior, and true indicates cloning behavior
$('ul li').click(function(){ console.log(this);});// jq object Clone (Boolean value) returns that the cloned node page does not exist. You need to append it to the page to see it. / / do not pass / false indicates no cloning behavior. True indicates cloning behavior $('button ') click(function(){ // var li = $('ul li').eq(0).clone(); var li = $('ul li').eq(0).clone(true); $('ul').append(li);});
Replace node
replaceAll: new node replaceAll('selector ')
replaceWith: $('reference node') replaceWith (new node)
var li = $('<p>This is illegal nesting</p>');// $('li').replaceWith(li); li.replaceAll('li');
Wrap node
// Chain calling principle: the object operated by the jq method or the object after the operation returns. / / 1 jq object Wrap ('label ') jq object is wrapped with a label $('span') wrap('<div></div>');// 2. jq object Wrapinner ('label '); jq object is wrapped with a label $('span ') wrapInner('<i>12345</i>');// 3. jq object Wrapall ('label ') jq object wrapped in a label var B = $('span') wrapAll('<p></p>');// 4. jq object unwrap(); jq object deletion and parent node deletion to body end var a = $('span ') unwrap(). unwrap(). unwrap(). unwrap(); console. log(a, b);
Event object
/* Event object: the first parameter of the event handler*/$('div').click(function(ev){ console.log(ev); // jQuery.Event console.log(ev.originalEvent); // Native event object console log(ev.type); // Event type console log(ev.target); // Trigger source console log(ev.delegateTarget); // Event binding object console log(ev.which); // Basically consistent with keyCode, it is more powerful than keyCode, and retains the left, middle and right 123 console of the mouse log(ev.screenX, ev.screenY); // The distance between the mouse and the console in the upper left corner of the screen log(ev.pageX, ev.pageY); // Mouse distance from the console in the upper left corner of the page log(ev.offsetX, ev.offsetY); // The distance from the mouse to the upper left corner of the div console log(ev.ctrlKey, ev.shiftKey, ev.altKey); // Whether the corresponding key is pressed when the event is triggered log(ev.clientX, ev.clientY); // The distance between the mouse and the visible area in the upper left corner of the screen / / prevent bubbles ev stopPropagation(); // Block default behavior ev preventDefault(); // Prevent bubbling + prevent default event return false// It is usually written at the end of the function})$ (document).contextmenu(function(){ // return false;});
Event binding
on
-
Bind the same event to the same element with different event handling functions
function a(){ console.log(1);}function b(ev){ console.log(ev.type);}// 1. jq object On ('event type ', event handler) $('div') on('click', a);$ ('div'). on('click', b);
-
Add the same handler to different events of the same element
jq object on('event type, event type 1, event type 2 ', event handling function)
$('div').on('click dblclick mouseenter mouseleave contextmenu', b);
-
Add corresponding event handling functions to different events of the same element
jq object on({property name: function}) property name - event type
$('div').on({ 'click': b, 'mouseenter': a, 'mouseleave': function(){ console.log(2); }, // 'click': a / / if the attribute names are the same, the following overwrites the previous});
-
Binding custom events
Custom event
$('div').on('abc', function(){ console.log('Ha ha ha ha ha ha ha');});// Manual triggering: jq objects Trigger (custom event type) setTimeout (function() {$('div '). trigger('abc'); / / manually trigger custom events}, 3000);
-
The implementation event delegate element can occur in the future
Event delegates: jq objects On (event type, selector, event handler)
$('div').on('click', 'p', function(){ console.log($(this).text());});$('div').append('<p>12345</p>');
Namespace
/* jq Object on(); jquery1. Delegate bind live above version 7*/// function a(){// console.log(1);// }// function b(ev){// console.log(ev.type);// }$('div').on('click.a', function(){ console.log(2);});$('div').on('mouseover.a', function(){ console.log(4);});
off
Event cancellation: jq object Off (event type, name of handler);
The name of the event handler is optional
/* jq Object on(); jquery1. Delegate bind live above version 7*/function a(){ console.log(1);}function b(ev){ console.log(ev.type);}$('div').on('click.a', function(){ console.log(2);});$('div').on('mouseover.a', function(){ console.log(4);});$('div').on('click', a);$('div').on('click', b);/* Event cancellation: jq object Off (event type, name of handler); The name of the event handler is optional*/// $('div').off('click', a);// $('div').off('click.a');// $('div').off('click');$('div').on('click', function (){ console.log(333);});// Cannot cancel event / / $('div ') off('click', function(){// console.log(333);// });$ ('div'). off('click');
one
One: the usage of on is exactly the same
Difference: one time event
// $('div').one('click', function(){// console.log(1);// });// Simulate one event $('div ') with on On ('click ', function() {console. Log (1); / / unbind event $(this).off('click');});
Composite event
Syntax: jq object hover();
Parameter is a function: this function is triggered by sliding in and sliding out events
The arguments are two functions: a slide in function and a slide out function
// $('div'). hover(function(ev){// console.log(ev.type);// });$ ('div'). Hover (function (EV) {$(this). HTML ('This is enter '); $(this). CSS ('background', 'Blue');}, Function() {$(this). HTML ('This is leave '); $(this). CSS ('background', 'green');});
ergodic
$.each
$. Each (data, function)
The function has two parameters. The first parameter is the index / property name, and the second parameter is the specific value
// 1. Traverse the collection $ Each ($('li '), function (I, V) {/ / console.log (I, V); $(V). CSS ('background','Red '); / / console.log (this); / / current element / / console.log (this = = V);})// 2. Traversing array var arr = ['a ',' B ',' C ','d', 'e']; $ Each (arr, function (I, V) {/ / console.log (I, V); / / console.log (this); / / current value / / console.log (v = = this);})// 3. Traversal object var obj = {Name: 'Peng Yuyan', height: 188, age: 18}; $ each(obj, function(k, v){ console.log(k, v);});
$().each
$(). Each (function)
The function has two formal parameters. The first formal parameter is the index, and the second formal parameter has a specific value
Cannot traverse object
// 1. Traverse the set $('li ') each(function (i, v) { // console.log(i, v); console.log(this);});// 2. Array var arr = ['a ',' 1 ', 2, 3, 4, 5]$ (arr). each(function(i,v){ console.log(i, v);});
extend
Shallow copy
Shallow copy: only compare the attribute names. If the attribute names are duplicate, overwrite the previous one with the later one
Return dest after splicing data
Tools: $ extend(dest, src, src);
var obj = { name: 'Zhang Yixing', height: 198, age: 33};var obj1 = { age: 18, tip: 'earn money'}// Tools: $ extend(dest, src, src); // Shallow copy: only compare attribute names. If the attribute names are duplicate, overwrite the previous ones with the later ones. / / dest after splicing data is returned. / / var objnew = $ extend(obj, obj1);// console. log(obj);// console. log(objnew);// console. log(objnew == obj);// The data in dest will be changed. You can use the following method / / $ extend({}, src, src1...)// var objnew1 = $.extend({}, obj, obj1);// console.log(objnew1);// console.log(obj);
Deep copy
Deep copy: $ extend(true, dest, src, src)
Principle: put $ When the first parameter of extend is set to true, it is a deep copy. Process: first check whether the attribute name is repeated. If not, copy the attribute name and attribute value. If the attribute name is repeated and one attribute value is not an object, overwrite the previous one with the latter one. If all are objects, compare the sub attributes and repeat the above process
var a = { name: 1, age:{ n: 30, l: 18 }, height: 188, xl: 8};var b = { name: 2, age: { n: 31, look: 19 }}var o = $.extend(true, {}, a, b);console.log(o);
animation
show,hide,toggle
-
show
show: no animation effect without parameters
Pass parameter has animation effect
show(speed, easing, fn); w + h + o
Speed: speed milliseconds fast slow
easing: linear swing
fn: callback function
$('button').eq(0).click(function(){ // $('div').eq(0).show(2000); // $('div').eq(0).show('slow'); $('div').eq(0).show(5000, 'linear', function(){ console.log(1); }); $('div').eq(1).show(5000, 'swing', function(){ console.log(2); });});
-
hide
hide: no animation effect without parameters
Pass parameter has animation effect
hide(speed, easing, fn); w + h + o
Speed: speed milliseconds fast slow
easing: linear swing
fn: callback function
$('button').eq(1).click(function(){ $('div').eq(0).hide(5000, 'linear', function(){ console.log(1); }); $('div').eq(1).hide(5000, 'swing', function(){ console.log(2); });});
-
toggle
toggle is hidden if there is one, but not displayed if there is one
toggle: no animation effect without parameters
Pass parameter has animation effect
toggle(speed, easing, fn); w + h + o
speed: fast slow
easing: linear swing
fn: callback function
$('button').eq(2).click(function(){ $('div').eq(0).toggle(5000, 'linear', function(){ console.log(1); }); $('div').eq(1).toggle(5000, 'swing', function(){ console.log(2); });});
slide
slide: change the height of the element
slideDown: display
slideUp: Stow
slideToggle: put it away if you have it and expand it if you don't
-
slideDown
slideDown: no parameter transfer has animation effect
Pass parameter has animation effect
slideDown(speed, easing, fn);
Speed: speed milliseconds fast slow
easing: linear swing
fn: callback function
$('button').eq(0).click(function(){ $('div').eq(0).slideDown(5000, 'linear'); $('div').eq(1).slideDown(5000, 'swing');});
-
slideUp
slideUp: no parameter transfer has animation effect
Pass parameter has animation effect
slideUp(speed, easing, fn);
Speed: speed milliseconds fast slow
easing: linear swing
fn: callback function
$('button').eq(1).click(function(){ $('div').eq(0).slideUp(5000, 'linear'); $('div').eq(1).slideUp(5000, 'swing');});
-
slideToggle
slideToggle: no parameter transfer has animation effect
Pass parameter has animation effect
slideToggle(speed, easing, fn);
Speed: speed milliseconds fast slow
easing: linear swing
fn: callback function
$('button').eq(2).click(function(){ $('div').eq(0).slideToggle(5000, 'linear'); $('div').eq(1).slideToggle(5000, 'swing');});
fade
fade: change the transparency of elements
fadeIn: Enter
fadeOut: hide
fadeToggle: hide if there is one, show if not
fadeTo: change a transparency
-
fadeIn
fade(speed, easing, fn)
There are animations when there are no parameters
$('button').eq(0).click(function(){ $('div').eq(0).fadeIn(5000, 'linear'); $('div').eq(1).fadeIn(5000, 'swing');});
-
fadeOut
$('button').eq(1).click(function(){ $('div').eq(0).fadeOut(5000, 'linear'); $('div').eq(1).fadeOut(5000, 'swing');});
-
fadeToggle
$('button').eq(2).click(function(){ $('div').eq(0).fadeToggle(5000, 'linear'); $('div').eq(1).fadeToggle(5000, 'swing');});
-
fadeTo
fadeTo(speed, to transparency, easing, fn)
$('button').eq(3).click(function(){ $('div').eq(0).fadeTo(5000, .5, 'linear'); $('div').eq(1).fadeTo(5000, .5, 'swing');});
animate
First kind
The first: jq object Animate (animation parameters, speed, easing, fn);
Animation parameters: object {'attribute': attribute value, 'attribute': attribute value}
Attribute values: numeric expressions with unit characters show, hide, toggle
Speed: motion speed in milliseconds. The default value is 400ms
easing: linear swing
fn: callback function
$('button').eq(0).click(function(){ $('div').animate({ // 'left': '+=100', // 'left': '400px', 'width': 'hide', 'top': 400 }, 2000, 'swing', function(){ console.log(1); });});
Second
Animate (animation parameters, animation configuration attributes)
Animation configuration properties optional: {}
Duration: exercise duration ms
Eating: linear swing
Step: callback function triggered by each animation step
complete: callback function after animation execution
Queue: whether the queue is triggered at the first time no matter where the animation is written if false is set
$('button').eq(1).click(function () { $('div').animate({ 'width': 400, 'height': 400 }, { 'duration': 2000, 'easing': 'linear', 'step': function () { console.log(1) }, 'complete': function () { console.log('complete') }, 'queue': true }).animate({ 'top': '400px', 'left': 400 }, { 'duration': 2000, 'queue': false });});
Stop Animation
stop
.stop(clearQueue, gotoEnd)
clearQueue: whether to clear the follow-up queue. true - indicates to clear. false - do not clear
gotoEnd: whether to reach the end value. true - directly to the end value. false - keep in the current value
$('button').eq(1).click(function(){ // $('div').stop(); // $('div').stop(true); // Indicates to clear the subsequent queue / / $('div ') stop(true, true); // Indicates that you want to clear the subsequent queue to reach the target value / / $('div ') stop(false, true); // Indicates that the subsequent queues will not be cleared to reach the target value});
finish
.finish()
Ends all animations and reaches the target value
$('button').eq(1).click(function(){ $('div').finish();});
Delay animation
. delay (time) ms
$('button').eq(0).click(function(){ $('div').animate({ 'width': 1000, height: 1000 }, 10000).delay(5000).animate({ left: 1000, top: 1000 }, 10000);});
queue
Problem: css is not an animation and will not enter the animation queue. It will not wait for the previous animation to be executed after the execution is completed
css is executed as soon as the animation starts
Manually queued: jq object queue(function() {/ / effect to be executed})
Problem after manual: all animations behind the queue are not executed
$('div').slideUp(1000) .slideDown(1000) // .css('background', 'yellow') . Queue (function (next) {$(this). CSS ('background ',' yellow '); / / next is a function next();}) slideUp(1000) . slideDown(1000);
. queue can be understood as being disobedient and helping other effects and code insertion. Subsequent animations are not satisfied with this operation and need to be served by a specific function
AJAX
advantage:
\1. Short user waiting time
\2. interactive
\3. The pressure on the server is relatively small
\4. Poor bandwidth requirements
Disadvantages:
\1. ajax support for search engines
\2. Destroy the forward and backward buttons
ajax:
Bottom layer: $ ajax
Advanced: $ get $.post
$.ajax
$.ajax({
url: request address, required
type: request method, get post
Data: transferred data a = 1 & B = 2 objects
success: the successful callback function 200 304 has a formal parameter, which is the returned data
error: the wrong callback function has formal parameters and returns the created ajax object
complete: the callback function after the request is completed has formal parameters and returns the created ajax object
Timeout: timeout ms
datatype: set the type of expected data returned by the request text html script json... JSON (not the expected data type, a flag)
Cache: whether to use cache (when the page address has been requested and the data has been saved)
});
$.ajax({ url: './banner.json', // url: './ banner1. json', type: 'get', // data: 'a=1&b=2' data: {a: 22, b: 333}, success: function(res){ console.log(res); }, Error: function (ERR) {console. Log ('error reporting ', ERR);}, Complete: function (COM) {console. Log ('request completed ', COM);}// timeout: 1 // dataType: 'text' dataType: 'json'});
$.get
Syntax: $ get(url, [data], [callback])
$.get('./banner.json', 'a=1',function(res){ console.log(res);});
$.post
Syntax: $ post(url, [data], [callback])
$.post('./banner.json', 'a=1',function(res){ console.log(res);});
The difference between get and post
get: the parameter is spliced behind the address. It is unsafe and has limited capacity. It is generally used to request data
post: the parameter is transmitted in the request header. It is relatively safe and has unlimited capacity in theory. It is generally used to submit data
jsonp
Error: cross domain problem
Access to XMLHttpRequest at 'https://p.3.cn/prices/mgets?skuIds=J_5089253&type=1' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error source: due to the restriction of the browser on the homology policy of js
Homology policy: the same address, the same port, the same protocol
Non homologous:
Different protocols
Same address, different ports
Different addresses
jsonp: json with padding
var url = 'https://p.3. cn/prices/mgets? skuIds=J_ 5089253&type=1';$. ajax({ url: url, success: function(res){ console.log(res); }, error: function(err){ console.log(err); }, Datatype: 'jsonp' / / tell jq to use jsonp for data request});
Note: jsonp only supports get requests, not post requests
Principle:
Dynamically add a script tag to the page and set src as the address to be accessed
var url = 'https://p.3. cn/prices/mgets? skuIds=J_ 5089253&type=1&callback=a';// Send data request $('button ') when clicking the button click(function(){ var sr = $('<script src="' + url + '"><\/script>'); $('body').append(sr);});
Data serialization
// Click the button to get the data $('button ') in the form Click (function() {/ / console.log($('form').serialize()) when there is a small amount of duplicate data; / / generate serialized data name value = value & name value = value / / user = 123 & password = 321 / / visitor console.log($('form').serializeArray()) when there is duplicate data; / / generate serialized array / *[ {name: user, value: 123}, {name: user, value: 123}, ] */});
Plug in extension
$.extend
Class method: $ extend({
Method name: processing function,
Method name 1: handler 1
})
// trim() native js removes the left and right spaces in the string. / / jq expands the plug-in for removing spaces. / / the spaces at the beginning and end var STR = '123 4'; console. log('(' + str + ')');$. Extend ({'lefttrim': function (string) {/ / String: string to remove the left space / / console.log (string); / / \ s space / ^ \ S + / / / console.log (string. Replace (/ ^ \ S + /, ''); return string. Replace (/ ^ \ S + /, '')}, 'righttrim': function (string) {/ / String: the string to remove the right space. return string.replace(/\s + $/, '')}}// You can directly get the string console without left and right spaces log($.leftTrim(str)); console. log($.rightTrim(str)); console. log($.rightTrim(str). length);
$.fn.extend
Object method: $ fn.extend({
Method name: processing function,
Method name 1: handler 1
})
// Get the pointing problem $. Of the middle / / this fn. Extend ({'getcenter': function() {/ / console.log (this); / / middle subscript of child node var num = $(this). Children(). Length / 2; / / console.log (Num); if (Num! = parseInt (Num)) {num = parseInt (Num);} else { num -= 1; } console. log(num); return $(this). children(). eq(num); }}); console. log($('ul'). getCenter());
Zepto
introduce
zepto: lightweight js Library
Official website: https://zeptojs.com/
github: https://github.com/madrobby/zepto
5 modules:
zepto event ajax form ie comes with it
When other modules need to be used, they need to be imported after importing the zepto file
The difference between and jq
zepto: cannot get the width and height of a hidden element
zepto: no innerWidth outerWidth
console.log($('div').width()); // Content + padding + border JQ: contentconsole log($('div'). offset()); // {left top width height} JQ: {left top} / / zepto: cannot get the width and height of hidden elements / / zepto: no innerwidth outerwidthconsole log($('div'). innerWidth()); // content + paddingconsole. log($('div'). outerWidth()); // content + padding + border + margin(true)
Mobile end events
tap: Click
Triggered after the mouse is raised
singleTap: Click
doubleTap: double click
longTap: long press 750ms
swipe: triggered when the sliding moves in the same direction for more than 30px
swipeUp: up
swipeDown: next
swipeLeft: left
Swiperright: right
$('div').on('tap singleTap doubleTap longTap swipe swipeUp swipeDown swipeLeft swipeRight', function(ev){ console.log(ev.type);});