Web API
DOM Manipulation (Documwnt Object Model)
Topic 6
DOM
It’s that basic data structure- The tree
DOM
Operational commonAPI
What are theDOM
The node’sattr
和property
What is the difference between
knowledge
DOM
nature
- 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
- DOM node operation
- Get DOM node
1. getElementById
var elem = document.getElementById("test") / / element (2) getElementsByTagName var ¶s = 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
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
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
- 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
- parsing
url
All the parts
BOM operation
knowledge
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
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
- 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
- Compatibility with earlier versions of IE
- Internet Explorer is used in earlier versions
attachEvent
The binding event - The lower version of IE is used very little, and many sites are already unsupported
- Low IE requirements, give up the interview
- 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
- 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
- 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
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
- Internet Explorer Compatibility Problems
- Internet Explorer is used in earlier versions
ActiveXObject
, andW3C
Different standards
readyState
- 0 – (uninitialized) not called yet
send()
methods - 1 – (load) called
send()
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
status
2xx
– Indicates that the request is successfully processed. For example, 2003xx
– Redirection is required, and the browser redirects directly4xx
– Client request error, such as 4045xx
– The server is faulty
- Cross domain
-
What is cross-domain
- The browser does not allow the same origin policy
ajax
Access other domain interfaces - Cross-domain condition: a different protocol domain name port is considered cross-domain
- The browser does not allow the same origin policy
-
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
.CDN
Theta 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
jsonp
Full name isJSON with Padding
Is a solution for cross-domain resource requests.- loading
http://xxx/a.html
There may not be one on the servera.html
The 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 describe
Cookie sessionStorage and localStorage
The difference between?- capacity
- Whether in
ajax
中 API
Ease of use
knowledge
-
cookie
- It is used for client and server communication
- But it has local storage, so it’s borrowed.
- use
document.cookie = ...
Get and modify
-
Disadvantages of cookies for storage
- The storage capacity is too small, only 4KB
- all
http
Requests are carried, which affects the efficiency of obtaining resources The API is simple
, need to be packaged to usedocument.cookie = ...
-
SessionStorage and localStorage
HTML5
Specially designed for storage, maximum capacity5M
- Easy to use API
localStorage.setItem(key,value)
localStorage.getItem(key)
IOS safari
In hidden mode,localStorage.getItem
complains- Unified use is recommended.
try-catch
encapsulation
From the interview questions to investigate knowledge points (1)
From the interview questions to investigate knowledge points (2)