The following content is the knowledge of moOCs course “Quickly Get the front-end technology and match the interview requirements of big companies”.
Scope and closure
② Scope and closure (Scenario)
DOM, BOM, events
④ Events and DOM
DOM
1. What data structure is DOM?
DOM (Document Object Model)
DOM tree, tree structure
- The DOM is essentially a tree, a tree parsed in HTML
2. DOM node operation API
getElementById()
: Gets the element by idgetElementsByTagName()
: Gets the element by tag nameA collection ofgetElementsByClassName()
: Gets the collection of elements by classquerySelectorAll()
: Gets the collection of elements by the tag
3. DOM structure operation
- Creating a node:
createElement('p')
, created a new one<p>
node - Node content assignment:
innerHTML
- Insert node:
appendChild()
- This method inserts a node that does not exist
- For existing nodes, move them
- Get the parent element:
node.parentNode
- Get child elements:
node.childNodes
- Deleting a node:
removeChild()
BOM
- Navigator: Contains information about the browser.
Properties: www.w3school.com.cn/jsref/dom_o…
- Screen: Contains information about the client display screen.
- Location: Contains information about the current URL.
- History: Contains the URL that the user visited (in a browser window).
Generic event binding (listening) functions
- General binding
<div>
<button id="btn1">A button</button>
</div>
function bindEvent( elem , type , fn ){
elem.addEventListener( type , fn )
}
const btn1 = document.getElementById('btn1')
bindEvent( btn1 , 'click' , e= > {
alert('clicked')})Copy the code
- Generic event binding (consider event brokers)
<div id="div1">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
</div>
<button id='btn'>To load more</button>
function bindEvent(elem, type, selector, fn) {
if (fn == null) {
fn = selector;
selector = null;
}
elem.addEventListener(type, (e) = > {
let target = e.target;
if (selector) {
// Proxy required
if(target.matches(selector)) { fn.call(target, e); }}else {
fn.call(target, e); // No proxy is required}}); }const div1 = document.getElementById("div1");
bindEvent(div1, "click"."a".function (event) {
event.preventDefault(); // Block the default event behavior
console.log(this.innerHTML);
});
const btn = document.getElementById("btn");
bindEvent(btn, "click".function (event) {
console.log("btn click");
console.log(this.innerHTML);
});
Copy the code
(1) Use e.target to get the trigger element
Matches is the trigger element
For example, an event broker can be used to pull down an infinite list of images and listen for clicks on each image.
HTTP, Ajax, cross-domain, storage
⑤Http, Ajax, cross-domain
storage
cookie
Set with document.cookie:
- Set the format to:
key = value
- Add keys that do not exist
- Overwrite existing keys
Ajax
Easy handwriting Ajax
function ajax ( url , successFn ){
const xhr = new XMLHttpRequest()
xhr.open( 'GET' , url , true)
// true asynchronous to avoid jamming, false synchronous
xhr.onreadystatechange = function() {
if( xhr.readyState == 4) {if( xhr.status == 200 ){
successFn(xhr.responseText)
}
}
}
xhr.send(null)}Copy the code
Combine handwritten Ajax with Promise
function ajax(url) {
const p = new Promise((resolve, reject) = > {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// true asynchronous to avoid jamming, false synchronous
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else if (xhr.status === 404) {
reject(new Error("404 not found")); }}}; xhr.send(null);
});
return p;
}
Copy the code
Actual use:
const url = "/data/test.json";
ajax(url)
.then((res) = > console.log(res))
.catch((err) = > console.log(err));
Copy the code
Common ajax plug-ins for real-world projects
-
Calling Ajax in JQuery: JQuery complete Ajax example
-
Fetch: Fetch
There are three points to note when using Fetch:
- When an HTTP status code representing an error is received, the
fetch()
Return to the Promise ofIt’s not marked reject,Even if the HTTP status code of the response is 404 or 500. Instead, it marks the Promise state as resolve (but returns the value of resolve)ok
Property set to false), which is marked reject only when the network fails or the request is blocked. fetch()
** can not accept cross-domain cookies; ** You can also not usefetch()
A cross-domain session is established. Other websitesSet-Cookie
The header field will be ignored.fetch
Cookies will not be sent. Unless you use itcredentials 的Initialization options. After August 25, 2017, the default credentials policy has changed tosame-origin
. Firefox has also been modified in version 61.0b13)
- When an HTTP status code representing an error is received, the
-
Axios: axios
Axios supporting Promise
HTTP
methods
The methods of traditional
- Get: Obtains data from the server
- Post: submits data to the server
Now, the methods of
- Get: Obtains data
- Post: Creates data
- Patch/PUT: submits data
- Delete: deletes data
Restful API
A new approach to API design
Traditional API design: treat each URL as a function;
Restful API design: Treat each URL as a unique resource
How to design as a resource?
- Use URL parameters as little as possible
Traditional API design: / API /list? pageIndex=2
Restful API design: / API /list/2
- Use method to indicate the operation type
- Traditional API design:
- Post request: / API /create-blog
- Get request: / API /update-blog? id=100
- Get request: / API /get-blog? id=100
- Restful API design:
-
Post request: / API /blog
-
Patch request: / API /blog/100
-
Get request: / API /blog/100
-
Three refresh operations
- Normal operation: enter URL in address bar, jump link, forward and backward, etc
- Manual refresh: F5, click refresh button, etc
- Force refresh: Ctrl+F5
Different cache policies for different refresh operations:
- Normal operation: Force cache valid, negotiate cache valid
- Manual refresh: The forced cache is invalid, but the negotiated cache is valid
- Force refresh: Force cache is invalid, negotiation cache is invalid