Web API

DOM Manipulation (Documwnt Object Model)

Topic 6

  • DOMIt’s that basic data structure
    • The tree
  • DOMOperational commonAPIWhat are the
  • DOMThe node’sattrpropertyWhat is the difference between

knowledge

  1. DOMnature
  • The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of a document (structure tree) and defines a way that programs can access the structure tree to change the structure, style, and content of the document.
<! DOCTYPE html> <html> <head> <meta charset="utf-8">
  <title>Document</title>
</head>
<body>
  <div>
    <p>this is p</p>
  </div>
</body>
</html>
Copy the code

  1. DOM node operation
  • Get DOM node
1. getElementById
var elem = document.getElementById("test") / / element (2) getElementsByTagName var &paras = document. GetElementsByTagName ("p"); / / set (3) getElementsByClassName var elements = document. GetElementsByClassName ('tab'); GetElementsByName // The getElementsByName method is used to select HTML elements that have the name attribute // Suppose a form is <form name="x"></form>
var forms = document.getElementsByName("x");
forms[0].tagName // "FORM"5. The querySelector // querySelector method returns the element node matching the specified CSS selector. If more than one node meets the matching criteria, the first matching node is returned. If no matching node is found, null is returned. var el1 = document.querySelector(".myclass");
var el2 = document.querySelector('#myParent > [ng-click]'); // The querySelector method fails to select CSS pseudo-elements. QuerySelectorAll // The querySelectorAll method returns all nodes matching the specified CSS selector, and returns objects of type NodeList. var matches = document.querySelectorAll("div.note, div.alert"); // The argument to the querySelectorAll method, which can be comma-separated CSS selectors, returns all elements matching one of the selectors.Copy the code
  1. property :A property of the js object
var pList = document.querySelectorAll('p') var p = pList[0] console.log(p.style.width) // Get the style p.style.width ='100px'Log (p.classname) // Get class // Get nodeName and nodeType console.log(p.nodename) console.log(p.nodetype)Copy the code
  1. attribute :
var pList = document.querySelectorAll('p')
var p = pList[0]
p.getAttribute('data-name')
p.setAttribute('data-name'.'imooc')
p.getAttribute('style')
p.getAttribute('style'.'font-size: 30px'// The attribute tag on the document <li class="li">
    <a href="#" data-name="a"></a>
</li>
Copy the code
  1. DOM structure manipulation
  • The new node
createElement

var div1 = document.getElementById('div1'Var p1 = document.createElement(var p1 = document.createElement('p'Div1.appendchild (p1) // Add the newly created elementCopy the code
  • Gets the parent and child elements
parentElement  childNodes

var div1 = document.getElementById('div1')
var parent = div1.parentElement

var child = div1.childNodes
div1.removeChild(child[0])
Copy the code
  • Remove nodes
var child = div1.childNodes
div1.removeChild(child[0])
Copy the code

Title seven

  • How do I detect browser types
    function isAndroid() {return /Android/.test(navigator.userAgent);
    }
    funcnction isIphone() {return /iPhone/.test(navigator.userAgent);
    }
    function isIpad() {return /iPad/.test(navigator.userAgent);
    }
    function isIOS() {return /(iPad)|(iPhone)/i.test(navigator.userAgent);
    }
    Copy the code
  • parsingurlAll the parts

BOM operation

knowledge

  1. navigator && screen
// navigator
var ua = navigator.userAgent
var isChrome = ua.indexOf('chrome')
console.log(isChrome)

// screen
console.log(screen.width)
console.log(screen.height)
Copy the code
  1. location && history
/ / the location property returns a read-only object, provides information on the current document's URL / / assume that the current site is http://user:[email protected]:4097/path/a.html?x=111#part1

document.location.href //"http://user:[email protected]:4097/path/a.html?x=111#part1"
document.location.protocol // "http:"
document.location.host // "www.example.com:4097"
document.location.hostname // "www.example.com"
document.location.port // "4097"
document.location.pathname // "/path/a.html"
document.location.search // "? x=111"
document.location.hash // "#part1"
document.location.user // "user"
document.location.password // "passed"// Jump to another url document.location.assign('http://www.google.com'// Reload document.location.reload(true// Reload from local cache first (default) document.location.reload(false) // Jump to another url, but the current document does not remain inhistory// The back button cannot be used to return to the current document.location.assign('http://www.google.com') / / the location object to a string, equivalent to the document. The location. The href document. The location. The toString () / /history
history.back()
history.forward()
Copy the code

The title eight

  • Write a generic event listener function
  • Describes the event bubbling process
  • For a page with an infinite drop-down load of images, how do you bind events to each image
    • Using the agent

The event

knowledge

  1. Generic event binding
Var BTN = document.getelementById ('btn')
btn.addEventListener('click'.function(event) {
  console.log('clicked'}) // Common event bindingfunction bindEvent(el, type, fn) {
  el.addEventListener(type, fn)
}
var a = document.getElementById('link')
bindEvent(a, 'click'.function(e) {e.preventDefault() // Prevents default behavior console.log('clicked')})Copy the code
  1. Compatibility with earlier versions of IE
  • Internet Explorer is used in earlier versionsattachEventThe binding event
  • The lower version of IE is used very little, and many sites are already unsupported
  • Low IE requirements, give up the interview
  1. The event bubbling
// html
<div id="div1">
    <p id="p1"> Activate </p> <p id="p2"> Cancel </p> <p id="p3"> Cancel </p> <p id="p4"</p> </div> <div id="div2">
    <p id="p5"> Cancel </p> <p id="p6"> Cancel </p> </div> // jsfunction bindEvent(el, type, fn) {
  el.addEventListener(type, fn)
}

var p1 = document.getElementById('p1')
var body = document.body

bindEvent(p1, 'click'.functionE.toppropagation () console.log() {// Stop Bubble Propagation()'activate')})bindEvent(body, 'click'.function(e) {// Bubble console.log('cancel')})Copy the code
  1. The agent
<div id="div1">
    <a href="#" id="a1">a1</a>
    <a href="#">a2</a>
    <a href="#">a3</a>
    <a href="#">a4</a> <! </div> var div = document.getelementById ('div1')
div.addEventListener('click'.function(e) {
  var target = e.target
  if (target.nodeName === 'A') {
    console.log(target.innerText)
  }
})
Copy the code
  1. Functions that perfect generic binding events
function bindEvent(el, type, selector, fn) {// If there is no third argument, selector = fnif (fn == null) {
    fn = selector
    selector = null
  }
  el.addEventListener(type.function (e) {
    var target
    if(selector) {target = e.target // whether the DOM node matches the selectorif (target.matches(selector)) {
        fn.call(target, e)
      }
    } elseVar div = document.getelementById ({fn(e)}})}'div1')
bindEvent(div, 'click'.'a'.function(e) {e.preventDefault() // Prevents default behavior console.log(this.innerhtml)}) var a = document.getelementById ('a1')
bindEvent(a, 'click'.function (e) {
  e.preventDefault()
  console.log(a.innerHTML)
})
Copy the code

Title nine

  • Write an Ajax by hand, without relying on third-party libraries
  • Several implementations across domains

Ajax

knowledge

  1. XMLHttpRequest
var xhr = new XMLHttpRequest()
xhr.open('GET'."/api".false)
xhr.onreadystatechange = function() {// The function is executed asynchronouslyif (xhr.readyState == 4) {
        if (xhr.status == 200) {
            console.log(xhr.responseText)
        }
    }
}
xhr.send(null)
Copy the code
  1. Internet Explorer Compatibility Problems
  • Internet Explorer is used in earlier versionsActiveXObject, andW3CDifferent standards
  1. readyState
  • 0 – (uninitialized) not called yetsend()methods
  • 1 – (load) calledsend()Method is sending a request
  • 2 – (Load completed)send()Method completes, and all response contents have been received
  • 3 – (Interaction) Parsing the response content
  • 4 – (done) Response parsing is complete and can be called on the client side
  1. status
  • 2xx– Indicates that the request is successfully processed. For example, 200
  • 3xx– Redirection is required, and the browser redirects directly
  • 4xx– Client request error, such as 404
  • 5xx– The server is faulty
  1. Cross domain
  • What is cross-domain

    • The browser does not allow the same origin policyajaxAccess other domain interfaces
    • Cross-domain condition: a different protocol domain name port is considered cross-domain
  • Three tags that can cross domains

    • <img src="xxx">
    • <link href="xxx">
    • <script src="xxx">
  • Three tag scenarios

    • <img>Used for dotting statistics, statistics sites may be other domains
    • <link><script>You can useCDN.CDNTheta is also in other domains
    • <script>Can be used toJSONP
  • Cross-domain precautions

    • All cross-domains must be approved by the information provider
    • If not, the browser’s same-origin policy is vulnerable
  • JSONP implementation principle

    • jsonpFull name isJSON with PaddingIs a solution for cross-domain resource requests.
    • loadinghttp://xxx/a.htmlThere may not be one on the servera.htmlThe server can dynamically generate a file according to the request and return it
    • In the same way in<script src="http://xxx.com/api.js">
    <script>
    window.callback = function(data) {console.log(data)} </ SCRPT > // below return callback({x:100, y: 200}) <script SRC ="http://xxx.com/api.js">
    
    
    function getBooks(){
        var script=document.createElement('script');
        script.setAttribute('type'.'text/javascript');
        script.setAttribute('src'.'http://test.com/bookservice.php?callback=displayBooks'); / / key callback = XXX document. The body. The appendChild (script). } getBooks();Copy the code
  • Set the HTTP header on the server

// Write the second parameter across domain names. It is not recommended to write it directly"*"
response.setHeader("Access-Control-Allow-Origin"."http://a.com, http://b.com")
response.setHeader("Access-Control-Allow-Headers"."X-Requested-With")
response.setHeader("Access-Control-Allow-Methods"."PUT, POST, GET, DELETE, OPTIONS"// Accept cross-domain cookie response.setheader ("Access-Control-Allow-Credentials"."true")
Copy the code

The title ten

  • Please describeCookie sessionStorage and localStorageThe difference between?
    • capacity
    • Whether inajax
    • APIEase of use

knowledge

  1. cookie

    • It is used for client and server communication
    • But it has local storage, so it’s borrowed.
    • usedocument.cookie = ...Get and modify
  2. Disadvantages of cookies for storage

    • The storage capacity is too small, only 4KB
    • allhttpRequests are carried, which affects the efficiency of obtaining resources
    • The API is simple, need to be packaged to usedocument.cookie = ...
  3. SessionStorage and localStorage

    • HTML5Specially designed for storage, maximum capacity5M
    • Easy to use API
    • localStorage.setItem(key,value)
    • localStorage.getItem(key)
    • IOS safariIn hidden mode,localStorage.getItemcomplains
    • Unified use is recommended.try-catchencapsulation

From the interview questions to investigate knowledge points (1)

From the interview questions to investigate knowledge points (2)