JavaScript detailed learning notes 3
1. Web APIs
1.1 basic relevance between web APIs and JS
1.1. 1. Composition of JS
- ECMAScript: Javascript syntax ----- fundamentals of JavaScript
- DOM: page document object model ---- Web APIs
- BOM: browser object model ---- Web APIs
1.1. 2. JS foundation stage and Web APIs stage
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hsv6e7cb-163936817321) (C: \ users \ Liujun \ appdata \ roaming \ typora user images \ image-20211205104518014. PNG)]
JS basic learning ECMAScript basic syntax paves the way for the later. Web APIs is the application of JS, and JS basic syntax is widely used for interactive effects
1.2 API and Web API
-
API: some pre-defined functions designed to provide applications and developers with the ability to access a set of routines based on some software or hardware, but access the source code disorderly, or understand the details of the internal working mechanism. (just be able to use it, and don't worry about how to implement the internal structure)
-
The simple understanding is that API is a tool for programmers to easily realize the functions they want to complete.
-
Web API: it is a set of APIs (BOM and DOM) provided by the browser to operate browser functions and page elements, mainly for browser interaction effects
-
Web API: generally, there are inputs and outputs (transfer parameters and return values of functions). Many web APIs are methods (functions)
-
MDN detailed API: https://developer.mozilla.org/zh-CN/docs/Web/API
-
Because there are many Web APIs, this stage is called Web APIs
2. DOM
2.1 DOM introduction
DOM: document object model, which is a standard programming interface recommended by W3C organization to deal with extensible markup language (HTML or XML)
DOM tree:
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zjrunefz-163936817322) (C: \ users \ Liu Jun \ appdata \ roaming \ typora user images \ image-20211205110421334. PNG)]
- Document: a page is a document, which is represented by document in DOM
- Element: all tags in the page are elements, which are represented by element in DOM
- Node: all contents in a web page are nodes (attributes, labels, text, comments, etc.), which are represented by node in DOM
- DOM treats all of the above as objects
2.2 getting elements
2.2. 1 how to get page elements
- Get by ID
- Get by tag name
- Obtained through the new method in HTML5
- Special element acquisition
// Because the document page is loaded from top to bottom, there must be a label first, so the script is written under the label // 1. Get according to the id. the id must be a string. Return a DOM element object matching the id. if it is not found under the current document, return null var timer=document.getElementById('time'); console.log(timer); // <div id="time">2021-12-12</div> console.log(typeof timer); // object console.dir(timer); // div#time prints the returned element object to better view the properties and methods inside // 2. Get according to the tag name and return the collection of obtained element objects. The element objects stored in the form of pseudo array are dynamic var lis=document.getElementsByTagName('li'); console.log(lis); // HTMLCollection(2) [li, li] console.log(lis[0]); // <li>Do you know, it should be green, fat, red and thin</li> // ergodic for(var i=0;i<lis.length;i++){ console.log(lis[i]); } // You can also obtain all child elements with specified tag names inside an element (parent element). The parent element must be a single object (which element object must be specified). The parent element itself is not included when obtaining // var ol=document.getElementsByTagName('ol'); // [ol] // console.log(ol[0].getElementsByTagName('li')); // HTMLCollection(2) [li, li] var ol=document.getElementById('ol'); console.log(ol.getElementsByTagName('li')); // HTMLCollection(2) [li, li] // 3. Get the object collection according to the class name through the new method in HTML5 var box=document.getElementsByClassName('box'); console.log(box); // HTMLCollection(2) [div#time.box, div.box, time: div#time.box] // 4. document.querySelector('selector '); Returns the first element according to the specified selector. The object selector is to be signed var boxs=document.querySelector('.box'); console.log(boxs); // <div id="time" class="box">2021-12-12</div> // 5. document.querySelectorAll('selector '); Returns a collection of all element objects according to the specified selector var allbox=document.querySelectorAll('.box'); console.log(allbox); // NodeList(2) [div#time.box, div.box] // 6. Acquisition of special elements // Get body element var bodys=document.body; console.log(bodys); // <body>...</body> console.dir(bodys); // body // Get html element var htmls=document.documentElement; console.log(htmls); console.dir(htmls); // html
2.3 event basis
2.3. 1. Three elements of event
An event is a behavior that can be detected by JavaScript. It is simply understood as a trigger response mechanism.
- Event source: the object whose event is triggered – > button
- Event type: how to trigger events, such as onclick, mouse passing, and keyboard pressing
- Event handler: completed by function assignment
<body> <button id="btn">Tang Bohu</button> <script> // 1. Event source var btn=document.getElementById("btn"); // 2. Event type // 3. Event handler btn.onclick=function(){ alert("Point Qiuxiang"); } </script> </body>
2.3. 2 execution event process
- Get event source
- Registration event (binding event)
- Add event handler (in the form of function assignment)
// Case: click the div console output and I am selected var div=document.querySelector("div"); div.onclick=function(){ console.log("I was chosen"); }
2.3. 3 common mouse events
onclick | Click the left mouse button to trigger |
---|---|
onmouseover | Mouse over trigger |
onmouseout | Mouse away trigger |
onfocus | Get mouse focus trigger |
onblur | Loss of mouse focus trigger |
onmousemove | Mouse movement trigger |
onmouseup | Mouse bounce trigger |
onmousedown | Mouse press trigger |
2.4 operation elements
2.4. 1 change element content
-
element.innerText: for the content from the start position to the end position, html tags will be removed, and spaces and line breaks will be removed (non-standard)
-
element.innerHTML: all contents from the start position to the end position, including html tags, while retaining spaces and line breaks (W3C standard)
<body> <button>Displays the current system time</button> <div>At a certain time</div> <p>123</p> <script> // element.innerText() var btn=document.querySelector("button"); var div=document.querySelector("div"); btn.onclick=function(){ // div.innerText='2019-6-6'; div.innerText=getTime(); } function getTime(){ // 1. Format date: mm / DD / yyyy H / min / S var data=new Date(); var year=data.getFullYear(); var month=data.getMonth(); var datas=data.getDate(); var hour=data.getHours(); var minutes=data.getMinutes(); var seconds=data.getSeconds() var arr=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; var day=arr[data.getDay()]; return 'Today is: '+year+'-'+month+'-'+datas+'- '+hour+':'+minutes+':'+seconds+' '+day; // Today is Saturday, November 4, 2021 } // Elements do not need to add events var p=document.querySelector('p'); p.innerText=getTime(); </script> </body>
2.4. 2 change element attributes
// Case: two buttons, click different buttons and different pictures will appear <body> <button id="zly">Zhao Liying</button> <button id="ym">Yang Mi</button><br> <img src="images/Zhao Liying.jpg" alt=""> <script> var zly=document.getElementById('zly'); var ym=document.getElementById('ym'); var img=document.querySelector('img'); ym.onclick=function(){ img.src='images/Yang Mi.jpg'; } zly.onclick=function(){ img.src='images/Zhao Liying.jpg'; } </script> </body>
2.4. 3. Attribute operation of form elements
<button>Button</button> <input type="text" value="Input content"> <script> // 1. Get element var btn=document.querySelector('button'); var input=document.querySelector('input'); // 2. Registration event btn.onclick=function(){ // input.innerHTML = 'clicked'; This is an ordinary box, such as the contents of the label // The value in the form and the text content can be modified through value input.value='It was clicked'; // If you want a form to be disabled, you cannot click disabled // btn.disabled=true; this.disabled=true; // this refers to the caller btn of the event function } </script>
2.4. 4 style attribute operation
-
element.style: inline style operation
<style> div{ width: 200px; height: 200px; background-color: pink; } </style> <body> <div></div> <script> var div=document.querySelector('div'); div.onclick=function(){ // The attributes in div.style adopt hump naming method this.style.backgroundColor='purple'; this.style.width='250px'; } </script> </body>
-
element.className: class name style operation will overwrite the original class name
<style> div{ width: 100px; height: 100px; background-color: pink; } .change{ background-color: purple; color: #fff; font-size: 25px; margin-top: 100px; } </style> <body> <div class="first">text</div> <script> // 1. Use element Style gets and modifies the element style. If there are few styles or the function is simple, it can be used var test=document.querySelector('div'); test.onclick=function(){ // this.style.backgroundColor='purple'; // this.style.color='#fff'; // this.style.fontSize='25px'; // this.style.marginTop='25px'; // 2. You can change the element style by modifying the element's className, which is suitable for situations with many styles or complex functions this.className='change'; // 3. If you want to keep the original class name, this.className='first change'; } </script> </body>
2.4. 5 exclusive thought
<body> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <button>Button 4</button> <button>Button 5</button> <script> // Get all button elements var btns=document.getElementsByTagName('button'); // btns gets a pseudo array for(var i=0;i<btns.length;i++){ btns[i].onclick=function(){ // Remove all button background colors first for(var j=0;j<btns.length;j++){ btns[j].style.backgroundColor=''; } // Change the current color to pink this.style.backgroundColor='pink'; } } </script> </body>
- Clear all elements (kill others)
- Style the current element (leave me alone)
- Note that the order cannot be reversed. Kill others first, and then set yourself
2.4. 6 user defined attribute operation
-
Get property value
-
element. Attribute: get the attribute value, but get the built-in attribute value (the attribute of the element itself)
-
element.getAttribute('attribute ') is mainly used to obtain custom attributes (standard) and our programmers' custom attributes
<body> <div id="demo" index="1"></div> <script> var div=document.querySelector('div'); // 1. element. attribute console.log(div.id); // demo // 2. element.getAttribute('attribute ') console.log(div.getAttribute('index')); // 1 </script> </body>
-
-
Set attribute value
-
element. Attribute = 'value': set the built-in attribute value
-
element.getAttribute('attribute ',' value '): set custom attribute value
// 3. elemnt. Attribute = 'attribute value' div.id='demo1'; console.log(div.id); // demo1 // 4. element.getAttribute('attribute ',' value ') div.setAttribute('scorll','123'); console.log(div.getAttribute('scorll')); // 123
-
-
Remove Attribute
-
element.removeAttribute('attribute ');
div.removeAttribute('scorll');
-
2.4.7 H5 custom attributes
The purpose of custom attribute is to save and use data. Some data can be saved to the page instead of the database
-
Set H5 custom properties
H5 specifies that the beginning of user-defined attribute = = data - = = is used as the attribute name and assigned value
<body> <div data-getTime='20'></div> <script> var div=document.querySelector('div'); console.log(div.getAttribute('data-getTime')); // 20 div.setAttribute('data-index',3); </script> </body>
-
Get H5 custom attribute
-
Get compatibility element getAttribute(‘data-index’);
-
H5 new element dataset. Index or element Dataset = = ['index'] = = ie 11
-
dataset is a collection that stores all custom attributes starting with data. Only data - can be obtained
-
If there are multiple = = - = = linked words in the custom attribute, the hump naming method shall be adopted when obtaining
<div getTime='20' data-index='2' data-list-name='andy'></div> <script> var div=document.querySelector('div'); console.log(div.getAttribute('getTime')); // 20 console.log(div.getAttribute('data-index')); console.log(div.getAttribute('data-list-name')); // H5 NEW console.log(div.dataset); console.log(div.dataset.index); // 2 console.log(div.dataset.listName); // andy </script>
-
2.5 node operation
2.5. 1 why learn node operations
It is easier to obtain elements by using node hierarchy
- Using parent-child sibling node relationship to obtain elements
- Strong logic, but poor compatibility
Overview: all contents in a web page are nodes (labels, attributes, comments, text, etc.). In DOM, nodes are represented by nodes
All nodes of the HTML DOM tree can be accessed through JavaScript, and all HTML elements (nodes) can be modified, created or deleted
The node has at least three basic attributes: nodeType, nodeName and nodeValue
-
Element node nodeType is 1
-
The attribute node nodeType is 2
-
The text node nodeType is 3 (text nodes include text, spaces, line breaks, etc.)
<body> <div class="box"> <span class="erweima">x</span> </div> <script> var box=document.querySelector('.box'); console.dir(box); </script> </body>
In actual development, node operation mainly operates on element nodes
2.5. 2 node level
Using DOM tree, nodes can be divided into different hierarchical relationships, commonly parent-child brother hierarchical relationships
- Parent node: node parentNode
- Child node: parentnode Chilenodes (standard) returns a collection of child nodes containing the specified node, which is a collection of immediate updates
- Child node: parentnode Children (non-standard) is a read-only attribute that returns all child element nodes. It only returns child element nodes
<body> <div class="box"> <span class="erweima">x</span> </div> <ul> <li>1</li> <li>2</li> </ul> <ol> <li>3</li> <li>4</li> </ol> <script> // 1. Parent node var erweima=document.querySelector('.erweima'); // var box=querySelector.querySelector('.box'); // The parent node closest to the element is obtained. If the parent node cannot be found, it is returned as null console.log(erweima.parentNode); // box // 2. Child nodes // DOM provides methods (APIs) to get var ul=document.querySelector('ul'); var lis=ul.querySelector('li'); // Child nodes obtain all child nodes of chileNodes, including element nodes, text nodes, and so on console.log(ul.childNodes); // NodeList(5) [text, li, text, li, text] console.log(ul.childNodes[0].nodeType); // 3 console.log(ul.childNodes[1].nodeType); // 1 // Get element nodes, so it is generally not recommended to use childNodes for(var i=0;i<ul.childNodes.length;i++){ if(ul.childNodes[i].nodeType==1){ console.log(ul.childNodes[i]); } } // 3. Child nodes console.log(ul.children); // HTMLCollection(2) [li, li] </script> </body>
- Return the first child node: parentnode If firstchild cannot be found, null is returned, including all nodes
- Return the last child node: parentnode If lastchild cannot be found, null will be returned, including all nodes
- Return the first child element node: parentnode Firstelementchild (compatibility problem, supported by IE9 or above)
- Returns the last child element node: parentnode Lastelementchild (compatibility problem, supported by IE9 and above)
<body> <!-- Child nodes operate on the first and last child elements --> <ol> <li>I am li1</li> <li>I am li2</li> <li>I am li3</li> </ol> <script> var ol=document.querySelector('ol'); console.log(ol.firstChild); // #text console.log(ol.firstElementChild); // <li>I'm Li1</li> console.log(ol.lastChild); // #text console.log(ol.lastElementChild); // <li>I'm Li3</li> // The actual development writing method has no compatibility problem and returns the first element console.log(ol.children[0]); // //< li > I'm Li1</li> // Returns the last element console.log(ol.children[ol.children.length-1]); </script> </body>
-
Next sibling node: node Nextsibling returns the next sibling node of the current element. If it cannot be found, it returns null, including all nodes
-
Next sibling element node: node nextElementSibling
-
Previous sibling node: node Previoussibling returns the previous sibling node of the current element. If it cannot be found, it returns null, including all nodes
-
Previous sibling element node: node previousElementSibling
There are also compatibility issues
<body> <div>I am div</div> <span>I am span</span> <script> var div=document.querySelector('div'); console.log(div.nextSibling); // #text console.log(div.previousSibling); // #text console.log(div.nextElementSibling); // <span>I'm span</span> console.log(div.previousElementSibling); // null </script> </body>
-
Encapsulate a compatibility function yourself
function getNextElementSibling(element){ var el=element; while(el=el.nextSibling){ if(el.nodeType===1){ return el; } } return null; }
2.5. 3 node creation and addition
-
Create node
document.createElement('tagname '): create HTML elements specified by tagName. Because these elements did not exist and were generated dynamically according to our requirements, we also call them dynamic creation element nodes
-
Add node
node.appendChild(child): adds a node to the end of the child node list of the specified parent node, similar to the after pseudo element in css
node. Insert before (child): adds a node to the front of the specified child node, similar to the before pseudo element in css
<body> <ul> <li>123</li> </ul> <script> // 1. Create element node var li=document.createElement('li'); // 2. Add element node var ul=document.querySelector('ul'); ul.appendChild(li); // Add later var lili=document.createElement('li'); ul.insertBefore(lili,ul.children[0]); // Add at specified location </script> </body>
2.5. 4. Deletion of nodes
- node.removeChild(child): deletes a child node from the DOM and returns the deleted node
<body> <button>delete </button> <ul> <li>Xiong Da</li> <li>Xiong er</li> <li>Bald head strength</li> </ul> <script> // 1. Get element var ul=document.querySelector('ul'); var btn=document.querySelector('button'); // 2. Delete element // ul.removeChild(ul.children[0]); // 3. Click the button to delete once btn.onclick=function(){ if(ul.children.length==0){ this.disabled=true; }else{ ul.removeChild(ul.children[0]); } } </script> </body>
2.5. 5 replication node (clone node)
node.cloneNode(): returns a copy of the node calling this method, also known as clone node / copy node
be careful:
- If the parenthesis parameter is empty or false, it is a shallow copy, that is, only the replication node itself is cloned, and the child nodes inside are not cloned
- If the parenthesis parameter is not empty or true, it is a deep copy, cloning not only the replication node itself, but also its child nodes
<body> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <script> var ul=document.querySelector('ul'); // 1. node.clonNode(); Shallow copy // var lis=ul.children[0].cloneNode(); // 2. node.cloneNode(true); Deep copy var lis=ul.children[0].cloneNode(true); // 3. Add ul.appendChild(lis); </script> </body>
2.5. 6 differences between three dynamic creation elements (interview questions)
- document.write(): it is the content stream that directly writes the content to the page, but when the document is executed, it will cause all pages to be redrawn.
- document.innerHTML(): write the content to a node, which will not cause page redrawing. It is more efficient to create multiple pages, but do not splice strings. Splice them in the form of array, with a slightly complex structure.
- document.createElement(): creating multiple elements is a little less efficient, but the structure is clearer.
- innerHTML is more efficient than createElement in different browsers.
<body> <button>click</button> <p>abc</p> <div class="inner"></div> <div class="create"></div> <script> // 1. document.write() var btn=document.querySelector('button'); btn.onclick=function(){ document.write('<div>123</div>') } // 2. document.innerHTML() var inner=document.querySelector('.inner'); // for(var i=0;i<100;i++){ // inner. InnerHTML + = '< a href = "#" > Baidu < / a >'; // } // Array efficiency var arr=[]; for(var i=0;i<100;i++){ arr.push('<a href="#"> Baidu < / a >); } inner.innerHTML=arr.join(''); // 3. document.createElement() var create=document.querySelector('.create'); for(var i=0;i<100;i++){ var a=document.createElement('a'); create.appendChild(a); } </script> </body>