• Nature of the DOM
  • DOM node operation
  • DOM tree structure operation
  • A few key objects: Navigator, Screen, Location, history
  • event
  • The event bubbling
  • The event agent
  • The HTTP status code
  • Cross-domain tags j and their special uses can be allowed
  • JSONP
  • cookie
  • localStorage
  • sessionStorage
  • Difference between the

The JS used by the front end (executed by the browser) generally consists of two parts:

1.JS basics (ECMA262 standard)

Js-web-api (W3C standard) : corresponding to DOM

BOM is the implementation of THE DOM by each browser vendor in their browser. Performance for different browser definitions are different, different implementation methods

  1. Window is a BOM object, not a JS object;

DOM(Document Object Model) Document Object Model

A few questions

1. What basic data structure is DOM? Tree structure

2. What is the difference between attributes and properties of DOM nodes?

Proterty refers to the property of a JS object;

Attribute is an HTML attribute

Nature of the DOM

W3C standard document, an HTML document that can be parsed by a browser to render a Web page

DOM node operation

1. Access to the DOM node: getElementById/getElementByTagName/getElementByClassName/querySelectorAll

/ / access elements var div1 = document. GetElementById (" div1 ") / / get set var divList = document. The getElementsByTagName (" div ") var classList = document.getElementsByClassName(".content") var pList = document.querySelectorAll("p")Copy the code

2. Property (js object’s property)

Var pList = document. QuerySelectorAll (" p ") var p = pList [0] / / access element styles console. The log (p. tyle. Width) / / modify the style p. tyle. Width = '100px' // get element class console.log(p.classname) // change class p.className = 'p1' // get nodeName and nodeType console.log(p.nodeName) console.log(p.nodeType)Copy the code

NodeName: div/a/p/span/h1 and so on

NodeType: number type. The normal DOM node is 1 and the text is 3. This can be used to distinguish node types

3. Attribute (HTML attributes) : getAttribute/setAttribute

Var pList = document. QuerySelectorAll (" p ") var p = pList [0] / / HTML attributes p.g etAttribute (' data - name ') / / set HTML attributes p.setAttribute('data-name', 'imooc') p.getAttribute('style') p.setAttribute('style', 'color: red')Copy the code

DOM tree structure operation

1. Add a node

2. Obtain the parent node

3. Obtain child nodes

4. Delete the node

Var p1 = document.createElement('p') p1. InnerHTML = 'this.is p1' div1.appendChild(p1)

Var p2 = document.getelementById ('p2') div1.appendChild(p2)

Copy the code

Var parent = div1.parentElement // Get the child node

Div1. removeChild(child[0]) var child = div1.childNodes

BOM (Browser Object Model) Browser Object Model

A few questions:

1. How to detect browser types, especially mobile android and IOS/ APP embedded browsers

2. How to disassemble the contents of the URL

A few key objects: Navigator, Screen, Location, history

var ua = navigator.userAgent
var isChrome = ua.indexOf('Chrome')

screen.width screen.height

Location. href location.protocol // Protocol type HTTP HTTPS location.pathname // routing address /learn/99 location.search // Parameters in url location.hash

Copy the code

history.back() history.forward()

event

Write a generic event binding listener function

Var BTN = document.getelementById ('btn1') btn.adDeventListener ('click', function(){ alert('clicked') }) // 2. Basic encapsulation, parameters (bound elements, event types, Function bindEvent(elem, type, fn){elem. AddEventListener (type, fn){elem. Var a = document.getelementById ('link1') bindEvent(a, 'click', function(e){ e.preventDefault() alert('a is clicked') })Copy the code

The method used by browsers with lower versions of IE is attachEvent

How do I bind events to each image on a page that scrolls down infinitely to load images

event

A general binding event function is perfected:

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <div id="div1"> div1 <p Id ="p1">p1</p> </div> </body> <script> Function bindEvent(elem, type, selector, fn){if(fn == null){fn = selector = null}

elem.addEventListener(type, function(e){ var target if(selector){ target = e.target if(target.matches(selector)){ fn.call(target, e) } }else{ fn(e) } }) }

Copy the code

var p1 = document.getElementById('p1') var div1 = document.getElementById('div1') bindEvent(div1, 'click', function(e){ alert('div1') }) bindEvent(p1, 'click', function(e){ // e.stopPropagation() alert('p1') }) </script> </html>

The event bubbling

The parent element is bound to a click event, and when the child element clicks, its click event bubbles, causing the parent element’s click event to occur

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>opacity</title> <style> .circle { border-radius: 50%; width: 20px; height: 20px; background: red; < span style = "max-width: 100%; clear: both; min-height: 1em;

< / head > < body > < div > < div id = "div1" > div1 p1 < p id = "p1" > < / p > < / div > < / div > < / body > < script > / / general binding of events to monitor function (updated version) / / Function bindEvent(elem, type, selector, fn){if(fn == null){fn = selector = null}

elem.addEventListener(type, function(e){ var target if(selector){ target = e.target if(target.matches(selector)){ fn.call(target, e) } }else{ fn(e) } }) }

Copy the code

var p1 = document.getElementById('p1') var div1 = document.getElementById('div1') bindEvent(div1, 'click', function(e){ alert('div1') }) bindEvent(p1, 'click', function(e){ // e.stopPropagation() alert('p1') }) </script> </html>

When clicking P1, it will alert p1 and then alert div1; If e.toppropatation () is added to prevent the event from bubbling, div1 will not pop

* Prevent bubbling: e.toppropatation ()

The event agent

Through proxy, click events can be added to the child nodes in batches. Click the child node to trigger the corresponding event

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <div id="div1"> <a>a1</a> <a>a2</a> <a>a3</a> <a>a4</a> </div> </body> <script> var div1 = document.getElementById('div1') Div1.addeventlistener ('click', function(e){var target = e.target if(target.nodename === 'A'){div1.adDeventListener ('click', function(e){ </script> </ HTML >Copy the code

Click which A TAB will pop up which a TAB content, developers can add different processing logic for different A tags on this basis

Advantages of proxy: 1. 2. Reduce the browser memory usage

Ajax requests and the Http protocol

Js manually write a cross-domain ajax realizing way # # # XMLHttpRequest http://www.w3school.com.cn/xmldom/dom_http.asp

let xhr = new XMLHttpRequest()
xhr.open("GET", "/api", false)
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
            alert(xhr.responseText)
        }
    }
}
xhr.send(null)
Copy the code

Tips:

Xmlhttprequest.open () initializes HTTP request parameters open(method, URL, async, username, password)

Parameter Description Method Indicates the HTTP method used for the request. Values include GET, POST, and HEAD.

The URL is the body of the request. Most browsers enforce a same-origin security policy and require the URL to have the same hostname and port as the text containing the script. Async False Synchronous, subsequent calls to send() will block until the response is fully received. If the argument is true or omitted, the request is asynchronous and usually requires an onReadyStatechange event handle. The username and password parameters are optional and provide authentication for the authorization required for the URL. If specified, they override any qualifications specified by the URL itself.

ReadyState Request status

The HTTP status code

Status Indicates the status of the request result

Cross domain

Cross-domain tags j and their special uses can be allowed

<img href= XXX > <script SRC = XXX > <img href= XXX > <link><script> can be used to request resources using CDN (CDN is also cross-domain) <script> can be used to implement cross-domain requests using JSONPCopy the code

JSONP

By loading the api.js file across domains and executing the callback method in that file, the data in window.callback here is the result of the request. Another way to cross domains is to set HTTP headers on the server side

storage

Understand the differences and characteristics of Cookie, sessionStorage and localStorege? What are the advantages of cookies versus the disadvantages later compared to sessionStorage and localStorege?

cookie

1. The storage is too small, only 4KB

2. All HTTP requests carry cookie information, which affects the efficiency of obtaining resources. Some requests actually do not need cookies

3 API simple, encounter more data, the need to partition storage must be encapsulated processing, otherwise it will directly exist in document.cookie = “… …” As a whole string

localStorage

1. New feature of HTML5, maximum 5M, will not carry extra in the request

2.API introduction is easy to use

localStorage.setItem(key, value)
localStorage.getItem(key)
Copy the code

sessionStorage

Difference between the

1. Capacity difference 2. Whether it is carried in ajax requests 3

This article is formatted using MDNICE