JavaScript
1. The relationship between JS and DOM
The browser has the function of rendering html code. The html source code forms a DOM object in the memory, which is the document object
There is a JS interpreter/execution/engine inside the browser, such as chrome using the v8 engine
We write a JS code in html, the JS code is executed by the engine, and the result of the execution is the DOM Operations, which are special effects we often see, such as pictures floating and text changing color
When the browser is executed, it will render when it encounters html code, and it will interpret and execute when it encounters js, so in order to ensure the overall display of the page , generally write js at the end, that is, render the page first, and then operate the DOM
2. Declaration of variables
var name = 'jquery';
Note:
Strictly case-sensitive;
Variable name: numbers, letters, underscores. Numbers cannot be used as the beginning of variable names. Variable names can also start with $ (not recommended)
Not using var will pollute global variables;
Adding var means declaring a local variable inside the function and assigning a value. If not, it is just an assignment process, and it will be searched outside. This variable
Debug:
console.log();
document.write(string);
alert(string);
3. Variable type
Three major categories (eight data types)
- Traditional type
Number (numeric type)
String(character String type)
Boolean(Boolean type)
- Composite type
Object(object type) Similar to the associative array in PHP {name: ' tom', age: 18}
’ s ’ s ’ ’ s ‐ ‐ ‐ ‐ ‐ tom', age: 18} (Function type)
- Special type
undefined (Undefined type)
If the variable is declared without an initial value, the data type of the variable is undefined.# No native data Composition:
1. Function name
- Numbers, letters, underscores, numbers cannot be used as the beginning of the function name.
- The function name should be as meaningful as possible. It is recommended to use the camel case naming rule for function names.
2. Parameters (optional), a function can have up to 255 parameters.
3. Function body.
4. Return value (optional)
Function declaration
1.function function name ([parameters...]){
Function body;
Return value;
}
2.var function name = new Function(parameter...function body);
3. Anonymous function
var test = function([parameter...]){
Function body;
Return value;
}
Function calling
1. Directly call the function name in the code segment.
2. Call the custom function in the form of a hyperlink.
> Call a custom function.
Scope of variables
Global scope and local scope
1. Global scope
Declared outside the function Variables, the scope is the global scope.
2. Local scope
Variables declared in the function body, the scope is the local scope.
4.Operation
Divided according to operation functions
-Arithmetic operations
- - * / % -- (positive) -(negative)
-Logical operations (JS, logical operations, return the earliest value that can determine the result of the expression) - Comparison operation
< /= %=
-Connecting operations (Once you encounter illegal numbers, the following is understood as "stitching")
## Divide by the number of operations
- Unary operation
exp2:exp3
When exp1 is true, execute exp2, otherwise execute exp3.
5. Branch statement
if
if...else ...
If...else if....
switch()
6. Loop
for
WHILE
…able ...
While and Do ... While:
Do ... While loop is The loop body will also be executed once when the loop condition is not met. while does not execute the loop body when the loop condition is not met.
7. JavaScript built-in objects
Everything in js can be understood as an object. When a method is called, it is packaged into an object at that moment
1. Object declaration
var o = new Object();
var o = {};
var o = {name:'tom',age:10}
2. Methods to access members in objects
Object name. Members (properties and methods) in the object
- String object
var s = new String();
var s = new String("hello");
var s = "hello";
Properties and methods
Properties:
length Get the length of the string Length
Method:
Object.indexof(substring)
Function: Determine the position where the substring first appears in the object. From Starting from 0
Return: Position. If the substring does not appear in the object, return -1.
Object.toUpperCase();
Function: Convert the object to Uppercase
Object.toLowerCase();
Function: Convert the object to lowercase
Object.substr(start [,length])
Function: String interception. The length length is intercepted from the start position.
The length optional parameter is not intercepted to the end of the string by default.
Object.slice(start[,end])
Function: String interception. Start interception from the start position and intercept until the end position. The end optional parameter does not intercept to the end of the string by default.
Object.replace(str1,str2)
- Array object
Statement:
var a = new Array();
var a = [];
var a = new Array('team',1);
var a = ['team',1...];
var a = new Array(7); //7 is the length of the array
Output of the array:
document.write(name of the array);
Assignment of the array
a[0] = 'nico';
Attribute:
length The length of the array
Method:
Array object.concat (Array object)
Function: Connect two array objects.
Return: the newly merged array. The order of the elements in the new array depends on the order of the two arrays when merging.
Array object.pop()
Function: Pop the last element in the array object.
Return: The popped (deleted) array element.
Array object.push(array element)
Function: Add elements to the end of the array.
Return: The length of the array after the added element.
Array object.shift()
Function: Pop an element from the head of the array
Return: The popped array element.
Array object.unshift(element name)
Function: Add elements to the head of the array
Return: The length of the array after the added element.
Array object.join(',')
Array object.split(',')
Array object.reverse()
Array object.sort()
- Date object
var d = new Date()
Method:
Object.getFullYear()
Function: Get four digits Year
Object.getMonth()
Function: Get the month, month (0~11)
Object.getDate()
Function: Get the day
Object.getHours()
Function: Get the number of hours
Object.getMinutes()
Function: Get minutes
Object.getSeconds()
Function: Get seconds value.
Object.getDay()
Function: Get the current week value (0 Sunday ~ 6 Saturday)
- Mathematics (Math) object
No instantiation, equivalent to PHP Static call through class name
Attribute:
PI assigned value
Method:
Math.ceil (variable)
Function: round up
Math.floor(variable)
Function: round down
Math.round(variable)
Function: Rounding
Math.abs(variable)
Function: Take absolute value
Math.random()
Function: Return pseudo Random value. Greater than or equal to 0 and less than 1 [0,1).
Math.max(variable..)
Function: Return the larger of the variables.
Math.min (variable..)
Function: Return the smaller of the variables.
8. Browser window object
Note: The window object is the browser host The object has nothing to do with JS language
Methods of window object:
window.alert(message);
window.confirm(message);
window.prompt();
window.open();
window.close();
window.print();
window.setInterval();
window.setTimeout();
window.clearInterval();
window.clearTimeout();
Sub-objects of the window object:
1.navigator browser information object
2.location address bar object
3.history History record
4.screen screen object
# 5.document object (DOM object)
6. Storage object
Web The storage API provides two storage objects: sessionStorage (session storage) and localStorage (local storage) to add, delete, modify, and query web page data.
sessionStorage is used to temporarily save the data of the same window (or tab page). These data will be deleted after closing the window or tab page.
LocalStorage is used to save the data of the entire website for a long time. The saved data has no expiration time until it is manually removed.
9.DOM object operation
DOM (Document Object Model Document Object Model)
Document HTML/XML
## (Extensible Markup Language) Object Convert HTML to JavaScript object. Model Model Find object - document.getElementsByTagName(HTML tag tag) Returns: an array of objects. - document.getElementsByName (name attribute value of the HTML tag) Returns: an array of objects. - document.getElementById( The id attribute value of the HTML tag) Returns: object. - document.getElementsByClassName (the class attribute value of the HTML tag) Returns: an array of objects. Why can window.document omit the previous window? Answer: It’s still a scope problem. If you can’t find it inside, look for it in the outer layer. There is window.document Model Model If the HTML document is regarded as an inverted tree structure. Then the document The HTML tags, text, comments, and attributes in can be regarded as nodes on the tree structure. The nodes are related. If you find one of the nodes, you can find all the nodes on the tree structure.
Note: A blank and a comment are all nodes; Node: node name (nodeName), Node type (nodeType). Some nodes have nodes Value (nodeValue). Parent node: node object.parentNode Child node: Node object.childNodes Return array (including blank nodes) ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ ‐ of
The last child node of the object
Sibling node:
Node object.previousSibling
Previous Sibling node
Node object. nextSibling
Next Sibling Node
document.createElement(HTML tag tag)
Function: Create a new HTML object
Return: Object
Parent object.appendChild(child object)
Function: Add the child object to the parent object.
Parent object.removeChild (parent object.lastChild)
Function: delete the last child node of the object.
Operation object
Properties
1. Reading of attributes
Object.Attribute name
2. Modification of attributes
Object.Attribute name = attribute value
Text
1. Read
Object.innerText
Object.innerHTML // All html codes in the tag
2. Modify
Object.innerText = modified text
Object.innerHTML = modified text
innerHTML parses HTML tags, innerText does not parse HTML tags.
Style
1. Read (because the style attribute is still followed by an object, so you need to use . to continue accessing, and you can only read the value of the internal style, and cannot read the value in <style>)
Object . style. Attribute name;
2. Modify
Object.style.Attribute name = attribute value;
Attribute name Note: background-color requires the "-" to be removed Then capitalize the first letter of the next word, that is, the small camel case attribute name.
3. Batch modify the style
Object.className = class style name
Get the runtime style object:
Obj.currentStyle[attr] and getComputedStyle(obj, null)[attr] are used to obtain
The former is only supported by IE and Opera, and the latter is also supported by IE9 and above in standard browsers. The second parameter Is a pseudo element
10.Event
1.Event source
All HTML tags can be regarded as event sources
2.Event
CLICK Click the event
DBLCLICK Double -click the event
Mouseover Mouse into
# Mouseout Mouse
## Keydown Keyboard Press Keypress keyboard Press # document loading # n blur lose focus change form change submit submit (belongs to the form element return false prevents submission) 3. Event Handler - <tag on event="Event handler"> Event handler can be javascript code or the name of a custom function. - Object.on event = event handler Event handler is an anonymous function.11. Timer Executed after n seconds Timer The clearTimeout() method can cancel the timing operation set by the setTimeout() method. The parameter of clearTimeout() method must be the ID value returned by setTimeout(). Note: To use the clearTimeout() method, use global variables when creating and executing scheduled operations: Timer executed every n seconds The setInterval() method can call a function or calculate an expression according to a specified period (in milliseconds). The setInterval() method will continue to call the function until clearInterval() is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.Tip: 1000 milliseconds = 1 second.
Tip: If you only want to execute it once, you can use the setTimeout() method.