Write in front:
When I was learning js before, I felt that this part was not well mastered, and this part is more important in js, so this part was organized systematically in case of emergency.
1. Function
1. Declaration and calling of functions in js
1). Statement:
function function name (parameter one, parameter two) { // function body code return return value }
2). Call
①Direct call: function name (parameter one, parameter two); ② Call by event: In the HTML tag, call by the event attribute
[Notes on function declaration and invocation]
① Whether there is a return value in the function only depends on whether there is a return in the function, no need to declare it deliberately In js, if there is a return value, it can be rejected; if there is no return value, it can also be accepted, and the result is undefined ②In js, the formal parameter list and the actual parameter list of the function have nothing to do with it That is, there are parameters that can be assigned no value (unassigned undefined); no parameters can also be assigned The actual number of arguments to the function depends on the argument list ③In js, the function is the only scope of the variable Then, the formal parameters of the function belong to the local variables of the function ④ There is no precedence between the declaration and the calling statement of a function. That is, you can call the statement first and then declare the function func() function func(){}
[Declaration and use of anonymous functions]
1). Anonymous function expression:
var func = function () {};
Call: func(); Note: The call statement of the function must be placed after the declaration statement
2). Directly assign an anonymous function to an event
window.onload=function(){}//Document ready function, ensure the code in the function, execute the code after the html document is loaded
document.getElementById("id").onclick=function(){}
3). Self-executing function
①! functon(){}();//Use at the beginning! Indicates that this is a self-executing function suggestion
!function(){ alert("Self-executing function 1"); }();
② (function(){}());//Include the anonymous function declaration and call with parentheses ---> indicate its integrity
(function(){ alert("Self-executing function 2"); })();
③ (function(){})();//Use parentheses to enclose the declaration statement of the anonymous function
(function(){ alert("Self-executing function 3"); })();
js code execution
1. Check the compilation stage
Mainly check for syntax errors, and perform operations such as variable declarations and function declarations.
2. Code execution stage
Execution statements such as variable assignment, function call, etc. belong to the execution phase of the code
var num=1; function func(){} var func2=function(){}
// check the compilation phase var num; function func(){} var func2; //code execution stage num=1; func(); func2(); func2=function(){}
【Arguments object】
1. Function: used to save the actual parameters of all functions >>>But when the function has actual parameters, you can use the array subscript to access all the actual parameters of the function >>>arguments[4]
2. The number of elements in arguments depends on the actual parameter list and has nothing to do with the number of formal parameters 3. Once the actual parameter is passed in when the function is called, the formal parameter of the corresponding position will be bound to the element corresponding to the arguments Modify the formal parameters, and the corresponding elements in the arguments will be changed. On the contrary, also established However, if there is no actual parameter passed in at a certain position, the formal parameters and arguments of that position will no longer be associated 4.arguments.callee(); Execute a reference to the current function, which is used to call itself recursively in the function
2. BOM operation
width height availWidth//Available width availHeight//Available height=screen.height-bottom taskbar height console.log(screen);//Attribute, belonging to windows object, windows can be omitted console.log(window.screen);
href: full url path protocol: protocol ming hostnamehostname port: port number host: host name + port number pathname: file path search: from? start parameter section hash: the part of the anchor starting with #
function gotoBaidu () { location.href="http://www.baidu.com"; }
// Jump to the page. After loading a new page, you can click the back button to go back function gotoBaiduByAssign () location.assign("http://www.baidu.com"); }
//Jump interface, there is no back button after loading a new page, you can't go back function gotoBaiduByReplace(){ location.replace("http://www.baidu.com"); }
// refresh the current page location.reload(); Refresh the page, if there is a local cache, it will be read from the cache, which is equivalent to pressing F5 location.reload(true);//Force refresh, re-fetching data from the server is equivalent to pressing Ctrl+F5
console.log(history.length);//The number of history pages used to record the current page jump history.forward();//Previous page history.back();//Next page console.log(history.length);//The number of history pages used to record the current page jump history.forward();//Previous page history.back();//Next page
console.log(navigator);
//Detect all plugins installed in the browser for(var i=0;i<navigator.plugins.length;i++){ console.log(navigator.plugins[i].name); }
1.prompt() pop-up input alert() popup output 2.confirm(""): prompt box with confirmation and cancellation. Return true and false respectively 3.close();Close the browser window 4.open(): open a new window Parameter 1: The address of the new window Parameter 2: The name of the new window, useless Parameter three: various configuration properties of the new window window.open("http://www.baidu.com","baidu","width=600px,height=600px,top=100px"); 5.setTimeOut(): Delayer Parameter 1: An anonymous function can be passed in, or a function name can be passed in Parameter 2: Delay in milliseconds Parameter three ~ parameter n: the parameter passed to the callback function setTimeout(function(num1,num2){},2000,"hahah",123); 6.setInterval(): Timer. Indicates how many milliseconds to execute the function Other usage is exactly the same as setTimeout 7.clearInterval(), clearTimeout(): clear timer, clear delayer When declaring a timer, you can accept the returned id and pass the id to clearInterval() to clear it
3. DOM manipulation
Divided into three categories: element nodes (label nodes), attribute nodes, and text sections Both attribute nodes and text nodes are children of element nodes. Therefore, when operating, you need to select the element node first, and then modify the attributes and text.
<ul> <li id="first"><b>第一项</b></li> <li class="cls" name="name">第二项</li> <li class="cls">Item 3</li> <li name="name">第四项</li> </ul> <div id="div1"> <ul> <li>The first item</li> <li class="cls" name="name">第二项</li> <li class="cls">Item 3</li> <li name="name">第四项</li> </ul> </div>
1) Use the getElement family of methods:
var li = document.getElementById("first"); var lis1 = document.getElementsByClassName("cls"); var lis2 = document.getElementsByName("name"); var lis3 = document.getElementsByTagName("li"Notes
①id cannot have the same name, and the first id is repeated ②When getting an element node, you must wait until the DOM tree is loaded before getting it Two ways: a.js is written at the end of the document b. The code is written in the window.onload function ③ The data obtained through the getElments series is in an array format, and each element must be obtained during the operation before the operation can be performed, and the array cannot be operated directly. document.getElementByTagName("li").click=function(){} × document.getElementByTagName("li")[0].click=function(){} √ ④ In this series of methods, you can also select a DOM node first, and select the required node from the selected DOM nodes: document.getElementById("div1").getElementByTagName("li");
2) Through the querySelector series method:
① Pass in a selector name and return the first found element. Typically used to find IDs: var dq1 = document.querySelector("#id"); ② Pass in a selector name and return all the elements found, no matter how many are found, they will be returned in array format. var dqs1 = document.querySelectorAll("#div1 li");
1. View the attribute node: .getAttribute("Attribute name"); 2. Set the attribute node: .setAttribute("attribute name", "attribute value"); 3. Notes: .setAttribute() has compatibility problems in older versions of IE, you can use the . symbol instead. document.getElementById("first").className = "haha";
1、 使用setAttribute设置class和style document.getElementById("first").setAttribute("class","class1");
document.getElementById("first").setAttribute("style","color:red;"); 2. Add a class selector using .className. document.getElementById("first").className = "class1"; 3. Use .style.style to directly modify a single style. Note that style names must use camel case document.getElementById("first").style.fontSize = "18px"; 4. Add a line-level style using .style or .style.cssText: document.getElementById("first").style = "color:red;"; // IE不兼容 document.getElementById("first").style.cssText = "color:red;"; // √
1. .innerHTML: Get or set the HTML code in a node. 2. .innerText: Get or set the text in a node, but cannot set HTML code.
1. .childNodes: Get all child nodes of the current node (including element nodes and text nodes). children: Get all element child nodes of the current node (excluding text nodes). 2. .parentNode: Get the parent node of the current node. 3. .firstChild: Get the first child node, including text nodes such as carriage return; .firstElementChild: Get the first element node. Does not contain text nodes. .lastChild, .lastElementChild get the last one, and the same is true. 4. .previousSibling: Get the previous sibling node of the current node, including text nodes; .previousElementSibling: Get the previous element sibling of the current node. .nextSibling、.nextElementSibling: 同理。 5. .attributes: Get all attribute nodes of the current node. Returns array format.
1. document.createElement("tag name"): Create a new node and return the created new node. Need to cooperate with .setAttribute() to set attributes for new nodes. 2. Parent node.insertBefore(new node, target node): In the parent node, insert the new node before the target node. Parent node.appendChild(new node): At the end of the parent node, insert a new node. 3. SourceNode.cloneNode(true): Clone a node. Passing in true means to clone the source node and all child nodes of the source node; Passing in false or not passing it means that only the current node is cloned, not the child nodes.
1. Parent node.removeChild(child node): From the parent node, delete the specified child node. 2. Parent node.replaceChild(new node, old node): From the parent node, replace the old node with the new node.
There are three types of objects in the html table:
1. Table object table= document.getElementById("table");
2. The row object table.rows[0]
3. Cell object table.rows[0].cells[0]
1.rows property, returns all rows of the current table, in array format
2.insertRow(index): Insert a new row in the index row of the table. Returns the newly generated row object
3.deleteRow(index): delete the index row of the table
1.cells property: returns all cell objects in the current row, in array format 2.rowIndex property, returns the subscript of the current row in the table 3.insertCell(index): indicates the index position in the row, inserts a new cell, return the newly generated cell object 4.deleteCell(index): means to delete the index-th cell in this row
1.cellIndex property: returns the subscript of the current cell in this row 2.innerHTML innerText etc.