Notes on common knowledge points of JavaScript

preface

js notes, a good memory is not as good as a bad pen. It summarizes some commonly used knowledge points. Send it to csdn as a backup. The previous ones are relatively simple, so I didn't write them. I only wrote some knowledge points that I think are easy to forget. If there are mistakes, please give me some advice.

JavaScript

1. Numerical conversion

Boolean() 		// Boolean non-zero is true
Number()  		// Only pure numeric strings can be converted to numbers, or NaN
parseInt() 		// When converting to int and rounding 3.14 - > 3 into a string, if 100A - > 100 does not start with a number, then NaN
				// Convert to decimal parseInt(nmuber)
parseFloat() 	// Convert to float to get floating point number
Math.ceil()     // Rounding up 3.1 - > 4
JSON.parse(str) // Parse string into object format
JSON.stringify(json)   // Convert object format to string

2. Scope

Find variables from the nearest parent, layer by layer up

let scope is within the nearest {}

3. Store data

Object data type, key value pair collection, json

4. Array

1. Set array length

// Example: array length-1 = > function: it can be used to delete the last element
arr.length = length

2. Add data from the back

// Return array length
push(value)

3. Add data before

// Return length
unshift(value)

4. Delete the last

// Returns the deleted element
pop()

5. Delete the first

// Returns the deleted element
shift()

6. Array inversion

// Returns the inverted array
reverse()

7. Delete some data

// Delete several data and choose whether to insert them. The default value (0, 0, no) returns a new array (deleted data)
splice(Start indexing, how many, value)

8. Array sorting

// Just change two without passing anything. Returns a sorted array
sort()        //For example: 1, 2, 3, 4 = > 2,1,4,3
// Sort from small to large
sort(function(a,b){return a - b})
// Sort from large to small
sort(function(a,b){return b - a})

9. Splice into string

// join (connector). Connect the array into a string with a connector and return the string
join('-')    // For example: 1, 2, 3 = > 1-2-3

10. Splicing array

// concat (other arrays) concatenates other arrays with arrays. Return the spliced array
arr1.concat(arr2)

11. Intercept array

// Default (0, array length), return the intercepted new array, not after the package
slice((start index, end index)

11. Find the index of value in the array

// If there is this data, the index that appears for the first time is returned. If not, - 1 is returned
indexOf(value)

12. Traversal array

// item is each element of the array, index is the index, and arr is the array. Parameters can not be written and have no return value
forEach(function(item,index,arr){}) 

13. Mapping array

// Returns a new array
map(function(item,index,arr){return item*10})  // Every element of the array * 10

14. Filter array

// Returns the filtered new array
filter(function(item,index,arr){return item>150}) // Delete elements of the array smaller than 150

15. Judge whether each item meets the conditions

// Returns a Boolean value
every(function(item,index,arr){return item>150})  // Determine whether it is greater than 150

16. Judge whether any item meets the conditions

// Returns a Boolean value
some(function(item,index,arr){return item>150})   // Judge whether there are elements satisfying more than 150

5. String

1. Get the character corresponding to the index position

// Character return
charAt((index)

2. Convert all letters of the string to lowercase

// Returns the converted string
toLowerCase()

3. Convert all letters of the string to uppercase

// Returns the converted string
toUpperCase()

4. Replace the first satisfied content of the string

// Returns a string. Note: first
replace(Replace the content, replace the content)

5. Remove the leading and trailing spaces

// Return string
trim()

6. Cut according to the separator to form an array

// Return array
split((separator)
// Multiple separators (x, y are separators)
split(/x|y/)
// If the separator is Add []
split(/[.]|y/)

7. Intercept string

There are three ways:

Substr (start index, number)

Substring (start index, end index)

Slice (start index, end index)

// Example
var arr = "01234567"
var res1 = substr(1,6)  	// The result is 123456, 1 is the start index and 6 is 6 characters
var res2 = substring(1,6)  	// Result 12345, 1 is the start index and 6 is the end index. Before package, not after package
var res3 = slice(1,6)		// Result 12345, 1 is the start index and 6 is the end index. Before package, not after package

6. Common digital methods

1. Obtain random decimal between 0 and 1.

// Returns a decimal number. Before and after the package, you can get 0, but not 1
Math.random()

2. Round numbers

// Returns an integer
Math.round(value)

3. Round up the numbers

// Returns an integer
Math.ceil(value)

4. Round down the number

// Returns an integer. Relative to decimals
Math.floor(value)

5. Exponentiation of numbers

// Return results 
Math.pow(Base, index)
// For example, the 5th power of 2
Math.pow(2,5)

6. Perform quadratic root operation on the number

// Return results
Math.sqrt(value)
// For example, root 4
Math.sqrt(4)

7. Perform absolute value operation on numbers

// Return results
Math.abs()

8. Get the maximum of several numbers

// Returns the maximum value.
Math.max(value1,value2,...)

9. Get the minimum of several numbers

// Returns the minimum value.
Math.min(value1,value2,...)

10. Get an approximation Π (Pie: 3.14159...)

// Return value
Math.PI 

11. Examples:

// Get a random integer between 0 and X,
var a = Math.random()*(x+1)
var result = Math.floor(a)
// Gets a random integer between X and y
var b = Math.random()*(y-x+1)
var result1 = Math.floor(b)+x

7. Time and common methods

var time = new data()
time.getFullYear()  // Acquisition year
time.getMonth()		// Get month
time.getDate()		// get date
time.getHours() 	// Get hours
time.getMinutes() 	// Get minutes
time.getSeconds()	// Get seconds
time.getDay()		// Get week 0 ~ 6, Sunday to Saturday
time.getTime()		// Get timestamp 	 1970 / 1 / 1 00:00:00 milliseconds from today

// Get time difference function
function getDiff(time1,time2){
    // Get timestamp
    var ms1 = time1.getTime()
    var ms1 = time1.getTime()
    // The number of seconds subtracted from two timestamps, rounded up to ignore milliseconds
    var sub = Math.celi((ms2-ms1)/1000)
    //Conversion, rounding down
    var day = Math.floor(sub / (60 * 60 * 24))
    var hours = Math.floor(sub % (60 * 60 *24) / (60 * 60))
    var minutes = Math.floor(sub % (60*60) / 60)
    var seconds = sub % 60
    
    return {day:day,hours:hours,minutes:minutes,seconds:seconds}
}

8.BOM operation

Operating browser

8.1 get browser window size

// Gets the width of the browser's visible window, including the scroll bar
window.innerWidth
// Gets the height of the browser's visible window
window.innerHeight

8.2 browser pop-up layer

// prompt box
window.alert('value')
// The query box has a return value. Confirm true and cancel false
window.confirm('value') 
// The input box has a return value. Confirm the input and cancel null
window.prompt('value')

8.3 opening and closing tabs

// open
window.open('address/url')
// Close current
window.close()

8.4 common browser events

// Resource loading completed
window.onload = function(){}
//Visual size change
window.onresize = function(){}
// Scroll bar position change
window.onscroll = function(){}

8.5 browser history operation

// Fallback page
window.history.back()
// Forward page
window.history.forward()

8.6 browser roll size

The size of the hidden part of the page when there is a scroll bar

// Height of roll off
document.documentElement.scrollTop  //The page has <! DOCTYPE html>
document.body.scrollTop				//There is no <! DOCTYPE html>
//Width of roll off
document.documentElement.scrollLeft
document.body.scrollLeft
// Height / width of roll out compatible writing
var height = document.documentElement.scrollTop || document.body.scrollTop

8.7 browser scroll to

// The width of left browser scrolling, the height of top browser scrolling, and instant movement
window.scrollTo(left,top)
//Smooth scrolling
window.scrollTo({
    left:xx,
    top:yy,
    behavior:'smooth'  //Smooth scrolling
})

9. Timer

If there is a return value, the number of timers is returned, regardless of the timer type

1. Interval timer (execute the specified code according to the specified cycle milliseconds)

setInterval(function(){
   // Code to execute
},1000)

2. Delay timer (execute the code once after a fixed time of milliseconds)

setTimeout(function(){
  // Code to execute
},1000)

3. Turn off the timer, regardless of timer type

// Grammar one
clearInterval(Return value of timer to be turned off)
// Grammar II
clearTimeout(Return value of timer to be turned off)

10.DOM

Properties and methods for manipulating content related to document flow

10.1 getting elements

// Get the element by id. There are - corresponding elements, not - null
document.getElementById('id name')
// Get the element according to the class name. Get the elements corresponding to all class names in the document stream and return a pseudo array
document.getElementsByClassName('Class name')
// Get according to the element tag name. Get the elements corresponding to all tag names in the document stream and return a pseudo array
document.getElementsByTagName('Tag name')
// Get one according to the selector, and get the first element in the document flow that meets the condition
document.querySelector('selector')   //Selector nav
// Select a group according to the selector, obtain all qualified elements in the document stream, and return a pseudo array
document.querySelectorAll('selector')

10.2 operation element content

// Text content
	// obtain
	element.innerText
	//Set override / replace
	element.innerText = 'New content'
// Hypertext content
	//obtain
	element.innerHTML
	//Set override / replace
	element.innerHTML = 'New content'

10.3 operation element attributes

// Native attributes (attributes that come with the tag)
	//obtain
	element.attribute
	//set up
	element.attribute = 'New content'
// Custom attributes (some attributes set by yourself)
	//obtain
	element.getAttribute('Attribute name')
	//set up
	element.setAttribute('Attribute name','Attribute value')
	//delete
	element.removeAttribute('Attribute name')

// Note: the above methods generally do not need to operate element class names and styles

10.4 operation element class name

//obtain
 element.className
//set up
 element.className = 'New class name'

10.5 operation element inline style

// obtain
 element.style.Style name
// set up
 element.style.Style name = 'Style value'  //There is a middle dash - style, written as a hump, such as backgroundColor

10.6 get element non inline style

// Get can get non inline style or inline style. You can only get it but not set it
window.getComputedStyle(element).Style name

10.7 node operation

// Create a node, create a specified label element, and return the node
document.createElement('Label name')
// Insert node is inserted backward, and the child node is placed inside the parent node and in the last position
 Parent node.appendChild(Child node)
// Insert the node forward, and put the child node inside the parent node at the specified position
 Parent node.insertBefore(The child node to insert, which child node is in front of it)
// Delete node, delete the specified node
 Parent node.removeChild(Child node)
// Delete node
 node.remove()
// Replace node
 Parent node.replaceChild(Replace the node, replace the node)
// Clone node true/false
 node.cloneNode(Clone descendant nodes)
// 1. Obtain the element size, the size of element content + padding + border area
 element.offsetHeight
 element.offsetWidth
// 2. Obtain the element size, the element content + the size of the padding area
 element.clientHeight
 element.clientWidth

11. Event type

  1. Figure error point: context menu is right-click

The event object is provided by the function and can be received with formal parameters in the function

Supplement:

offsetX and offsetY are the coordinate information of the mouse relative to the triggering event element

clientX and clientY are relative to the visual window and the coordinate information of the mouse

pageX and pageY are relative to the entire page document flow and the coordinate information of the mouse

2. Browser corresponding event mechanism

First pass from the outer layer to the inner layer (event capture stage), and then pass it out (event bubble stage)

3. Prevent the event from spreading

Event object.stopPropagation()

4. Event delegation

Use the target of the event object to know which element is clicked

ul.onclick = function(e){
    if(e.target.tagName === 'LI'){
        console.log('What you click is LI')
    }
}

12. Object oriented

Create factory

Constructor capitalized with new (built-in constructor Object)

Don't just return. Return the basic data type is invalid; Return complex data types, such as arrays, have invalid constructors.

function Person(){
    this.name = 'jack'
}
var obj = new Person()     // It's OK not to write parentheses. It's not recommended

If there is a function in the constructor, each object will create a new function

Solution: use the prototype prototype attribute, which is an object.

The attribute is written in the constructor body, and the method is written on the constructor prototype. If the attribute remains unchanged, it is also written on the prototype

// This method is added to all instantiated objects
function Person(){}
Person.prototype.sayHi = function(){}   //sayHi method name
Person.prototype.a = 110

13. Prototype chain

Object chain structure connected by "proto"

Object access mechanism: first find the proto on yourself, if not, find the proto of the most advanced object level by level, and if not, return undefined

14.ES6

14.1 naming of new variables

Before ES6, VAR was used to add let/const

var function scope

14.2 arrow function

The abbreviation of function expression in ES6 (declarative function cannot be used) is to change function into = >

var fn1 = function(){}
var fn1 = ()=>{}
// 1. When there is only one formal parameter, you can not write ()
var fn1 = function(a){}
var fn1 = a=>{}
// 2. When there is only one sentence, you can not write {}, and the result of this sentence will be regarded as the return value
var fn1 = function(a,b){return a+b}
var fn1 = (a,b)=> a+b
// 3. The arrow function has no arguments
// 4. There is no this inside the arrow function, but this in the external scope is used

14.3 deconstruction assignment

// Deconstruct array, using []
let arr[a,b] = ['1','2']
console.log(a)   // 1
console.log(b)	 // 2
// Deconstruct object, using {}
let obj = {name:lhd, id:10}
let{name,id} = obj
console.log(name) //lhd
console.log(id) //10
// Deconstruction object alias
let{name:a} = obj  //a=lhd

14.4 template string

You can wrap lines and parse variables directly in the string

var str = `ab`
var str = `a
b`
// Analytic variable
var age = 18
var str = `I this year ${age}year`  // I am 18 years old

14.5 expansion operator

Expand array = Remove []

var arr = [1,2,3]
console.log(arr)      //Output array
console.log(...arr)   //Output 1,2,3
// Function 1: merge arrays
var arr = [1,2,3]
var arr1 = [4,5,6]
var arr2 = [...arr,...arr1] // Output array [1,2,3,4,5,6]
// Function 2: pass parameters to function
var arr1 = [10,20,5,6]
var max = Math.max(...arr1)  //Output the maximum value. max() cannot be placed directly in the array

Expand object = remove {}

// Function 1: used to copy objects. Note: there are the same members Obj should be placed in front, otherwise it will be covered by obj
var obj = {name:lhd}
var obj1 = {
    id: 10,
    ...obj
}

14.6 class syntax

ES6 syntax writes constructors, which solves the disadvantage that constructors need to be written separately before writing

// Previous writing
function Person(name,age){
    this.name = name
    this.age = age
}
Person.prototype.sayHi = function(){ console.log('hello world')}
// Static properties and methods
Person.a = 100
Person.go = function(){ console.log('go') }
// Instantiate object
var p1 = new Person('lhd','19')
console.log(p1)					  	// Output object
p1.sayHi()							// Output hello world
console.log(p1.a)					// Output 100
Person.go()							// Output go
var p2 = Person('lhd','19')         // Note: no error is reported, but the object cannot be instantiated

// ES6 writing method
class Person{
    // This is written according to the constructor body of ES5
    constructor(name,age){
        this.name = name
    	this.age = age
    }
    // Functions that write prototypes directly
    sayHi(){ console.log('hello world')}
    // Static attribute + static
    static a = 100
	// Static method 
	static go() = function(){ console.log('go') }
}
// Instantiate object
var p1 = new Person('lhd','19')
console.log(p1)
p1.sayHi()
var p2 = Person('lhd','19')        // Note: when reporting an error, be sure to use new
console.log(Person.a)
Person.go()

15. Execute the function immediately

The statement preceding the immediate function must have a semicolon

(function(){
    // xx
}())

16. Request interface

The back end provides interface documents, which are written according to the interface documents

16.1 Ajax

var xhr = new XMLHttpRequest()
xhr.open('GET','XXX',true)    //Request method, request address, asynchrony
xhr.onload = function(){
    //Returns a string
    console.log(xhr.responseText)
    //If you want to get json, you need to parse it
    var res = JSON.parse(xhr.responseText)
}
xhr.send()

16.2 difference between get and POST

GET is spliced directly in the address of the open function

xhr.open('GET','xxx?name=lhd&id=10',true)    //Request method, request address, asynchrony

POST writes parameters in the send function and requires special instructions

// Syntax: XHR Setrequestheader ('content type ', the parameter format you passed) back end to the parameter format
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send('name='+lhd+'&id='+age)

16.3 prevent default submission of form

loginForm.onsubmit = function(e){
    e.preventDefault()               
}

17.jQuery

A large and simple third-party class library encapsulates DOM operations and exposes two global variables $and jquery after introduction

17.1 selector

(returns a collection of elements)

$('selector')

17.2 filter

$('selector').Filter name()

17.3 operation text

$('div') = selected div

3.1 html() is equivalent to innerHTML of native JS

// obtain
$('div').html()
// set up
$('div').html('What you want to set')
// You can recognize and parse html structure strings
$('div').html('<h2>hello world<h2>')

3.2 text() is equivalent to innerText of native JS

// obtain
$('div').text()
// Settings cannot be resolved
$('div').text('hello world')

3.3 val() is equivalent to value in native JS

// obtain
$('input').val()
// set up
$('input').val('What you want to set')

17.4 operation element class name

4.1 addClass() new class name

$('div').addClass('Class name to add')

4.2 removeClass() delete class name

$('div').removeClass('Class name to delete')

4.3 toggleClass() switch class name

If it has this class name, it is deleted. If it does not have this class name, it is added

// Suppose div has three class names a, B, C, D
var btn = document.querySelector('button')
btn.onclick = function(){
    $('div').toggleClass('box')
}
// Click once to add box to the class, and click the second time to delete box

17.5 operation element style

1.css()

// Get, you can get inline and non inline styles.
// Element collection CSS (the style name you want to get)
$('div').css('width')     //Gets the width of the div

//Note: when the style unit is px, px can be omitted
//Element collection CSS (style name, style value)
$('div').css('width', '300px')    //Set the div width to 300px
$('div').css('width', 300)

2.css batch setting style

// Element collection css({all styles to set})
$('div').css({
    width:260,
    height:320,
    'background-color':'purple'
})

17.6 operation element attribute

1.arrt()

// It is generally used to manipulate custom attributes of elements. Appear directly in the label of the element

// Get custom attribute hello
$('div').attr('hello')
// Set custom properties hello
$('div').attr('hello') = 100

2.removeAttr()

// Delete custom attribute hello
$('div').removeAttr('hello')

3.prop()

// When you manipulate the element's native attribute, it will appear directly in the element tag
// When operating a custom attribute, it will not appear directly in the element tag, but will respond on the element object
// Note: prop() cannot get the original custom attributes on the element label, but can only get the custom attributes set by prop()

// Get native and custom properties
$('div').prop('id')
$('div').prop('hello')
// Set native and custom properties
$('div').prop('id') = 1 
$('div').prop('hello') = 100

4.removeProp()

// You cannot delete the original custom attributes and native attributes. You can only delete the custom attributes set by prop()
$('div').prop('hello') = 100
$('div').removeProp('hello')

17.7 obtaining element dimensions

1.width(),height()

// Gets the size of the content area
$('div').width()     		// 300
$('div').height()			// 300

2.innerWidth(),innerHeight()

// Get content and padding area size
$('div').innerWidth()		// 340
$('div').innerHeight()		// 340

3.outerWidth(),outerHeight()

// Get content, padding and border area size
$('div').outerWidth()		// 380
$('div').outerHeight()		// 380

4.outerWidth(true),outerHeight(true)

// Get content, padding, border, and margin dimensions
// Suppose margin is set to 20px
$('div').outerWidth(true)		// 420
$('div').outerHeight(true)		// 420

17.8 get element offset

1.offset()

// Gets the coordinate position of the element relative to the upper left corner of the page
// The return value is the object data type {top:xx,left:xx}
$('div').offset()

2.position()

// Gets the location of the element
// The return value is the object data type {top:xx,left:xx}
// Note: if the positioning setting is right and bottom, it will automatically turn to top and left
$('div').position()

17.9 binding events

1.on()

1-1 basic binding events

// Syntax: collection of elements on('event type ',' event handler ')
$('div').on('click',function(){ console.log('click div') })

1-2 delegate binding events

// Syntax: collection of elements on('event type ', selector, event handler)
// Bind the event to the div element, and execute the event handling function when the p element in the div triggers the event
// Bind the element of the delegate to the div of the event
$('div').on('click','p',function(){ console.log('click p') })

1-3 batch binding events

// Syntax: collection of elements on({event type 1: handler, event type 2: handler})
// Note: event delegation is not allowed
$('div').on({
    click: function(){ console.log('Mouse click') }
    mouseover: function(){ console.log('Mouse in') }
    mouseout: function(){ console.log('Mouse out') }
})

2.one()

one() binds events in the same way as on(), except that one() can only be executed once

2-1 basic binding events

$('div').one('click', function(){ console.log('Trigger only once') })

2-2 event delegation

$('div').one('click','p', function(){ console.log('Trigger only once') })

2-2 batch binding events

$('div').one({
    click: function(){ console.log('Click the mouse and trigger it only once') }
    mouseover: function(){ console.log('When the mouse moves in, it is triggered only once') }
    mouseout: function(){ console.log('When the mouse moves out, it is triggered only once') }
})

3.hover()

A special event in jQuery

// Syntax: collection of elements Hover (function triggered when moving in, function triggered when moving out)
// When only one function is passed, this function will be triggered when moving in and out
$('div').hover(
	function (){ console.log('Mouse in') }
    function (){ console.log('Mouse out') }
)

4. Common event functions

jQuery makes some of our most commonly used events into event functions

We call these event functions to achieve the effect of binding events

Such as click(), mouseover(), mouseout(), change()

$('div').click(function(){ console.log('Mouse click') })

17.10 event unbinding and triggering

1. Off event unbinding

1-1 unbind all event handling functions

// Prepare event handler
function A() { console.log('A Event handler') }
function B() { console.log('B Event handler') }
function C() { console.log('C Event handler') }
// Bind events to div elements
$('div')
	.click(A)
	.click(B)
	.click(C)

// Event unbound syntax: collection of elements Off (event type)
// Remove all event handling functions corresponding to the click event of div
$('div').off('click')

1-2 unbind the specified event handler

// Syntax: collection of elements Off (event type, event handler to be unbound)
// The B event handler corresponding to the click event of div will be removed
$('div').off('click',B)

2. Trigger event

// Syntax: collection of elements Trigger (event type)
// click event handler that triggers div element
$('div').trigger('click')

17.11 basic animation

1.hide() hide animation

2.show() display animation

3.toggle() switch animation

=>If it is displayed, it is switched to hidden

=>If it is hidden, switch to display

The three functions have three parameters. The distribution is the movement time, movement curve and callback function after the movement

// 1. Write only one parameter: movement time, in ms
$('div').hide(1000)
$('div').show(1000)
$('div').toggle(1000)
// 2. Write all parameters
$('div').hide(1000,'linear', function(){ console.log('End of animation') })
$('div').show(1000,'linear', function(){ console.log('End of animation') })
$('div').toggle(1000,'linear', function(){ console.log('End of animation') })

17.12 folding animation

It is the same as the above animation, but the effects of hiding and displaying are different

The basic animation reduces the width and height to the upper left corner at the same time, while the folding animation only changes the height and reduces from bottom to top

1.slideDown() hide animation

2.slideUp() display animation

Toggle () animation

=>If it is displayed, it is switched to hidden

=>If it is hidden, switch to display

The three functions have three parameters. The distribution is the movement time, movement curve and callback function after the movement

// 1. Write only one parameter: movement time, in ms
$('div').slideDown(1000)
$('div').slideUp(1000)
$('div').slideToggle(1000)
// 2. Write all parameters
$('div').slideDown(1000,'linear', function(){ console.log('End of animation') })
$('div').slideUp(1000,'linear', function(){ console.log('End of animation') })
$('div').slideToggle(1000,'linear', function(){ console.log('End of animation') })

17.13 fade in animation

It is the same as the above animation, but the effects of hiding and displaying are different

Instead of changing the transparency, let the element disappear slowly

1.fadeIn() hide animation

2.fadeOut() display animation

3.fadeToggle() switch animation

=>If it is displayed, it is switched to hidden

=>If it is hidden, switch to display

The above three functions have three parameters, and the distribution is the motion time, motion curve and callback function after the end of the motion

4. Fadeto (motion time, specified transparency, motion curve, callback function) changes the transparency of the element to the specified value

// 1. Write only one parameter: movement time, in ms
$('div').fadeIn(1000)
$('div').fadeOut(1000)
$('div').fadeToggle(1000)
// 2. Write all parameters
$('div').fadeIn(1000,'linear', function(){ console.log('End of animation') })
$('div').fadeOut(1000,'linear', function(){ console.log('End of animation') })
$('div').fadeToggle(1000,'linear', function(){ console.log('End of animation') })
// 3.fadeTo() change transparency
$('div').fadeTo(1000,0.68,'linear',function(){console.log('Move to specified transparency') })

17.14 integrated animation function

animate() has four parameters

=>First: the style to be moved, passed as an object data type

=>Second: exercise time

=>Third: motion curve

=>Fourth: callback function at the end of motion

Note: styles related to color and transform cannot move

$('div').animate({
    width:500,
    height:600
},1000,'linear',function(){console.log('End of movement')})

17.15 motion end function

When you keep clicking the button to change the animation, the number of times will be recorded. Even if you stop, you will continue to change until all the times are executed

1.stop()

=>When any element executes the stop method, it will immediately end all current motions.

=>The current movement to that position, stay in that position.

=>Generally, when the animation ends, it is before the motion starts

// Basic Usage 
$('div').stop()
// Suppose a button id is btn, click to switch the animation
$("#btn").click(function(){
    // After adding stop(), click continuously. As long as you don't click, you will only execute until the end of this time, and will not continue to execute all times
    $('div').stop().toggle(2000)
})

2.finish()

It will immediately end all the current motion and go directly to the end of the animation

// Basic Usage 
$('div').finish()
// Write animation function by completing animation function
$("#btn").click(function(){
  	// At each trigger, the previous animation will be completed instantly, and only the latest animation will be executed
    $('div').finish().toggle(200)
})

17.16 ajax

Syntax: $ ajax({configuration item for sending ajax this time})

Configuration item:

1.url: required, indicating the request address

2.method: optional; GET by default; indicates the request method

3.data: optional; the default value is' ', indicating the parameters carried to the backend

5.dataType: optional, automatically recognized by default, indicating the data type returned to you by the backend

6.async: optional; the default is true, indicating whether it is asynchronous

7.success: optional, indicating the callback function of successful request

8.error: optional, indicating the callback function of the request failure

// Demonstrate sending two data to the backend
$.ajax({
    url:'http://localhost:8888/test',
    method:'POST',
    data:{name:'lhd',id:'19'},
    dataType:'JSON',
    async:'true',
    success:function(res){
        console.log(res)   //Output back-end json to you
    }
})


// Example: get all the information in the form to the back end
$('form').on('submit', function(e){
    // Block default behavior
    e.preventDefault()
    const data = $('form').serialize()   // Get all input information
	$.post('http://localhost:8888/user', data, res=>{
    	console.log(res)
	})
})


// Example: user logout
$.get('http://localhost:8888/logout',{id:id},res=>{
    // Refresh the page directly after logging out
    window.location.reload()
})

18.webStorage

The storage size is 5M, which is different for different browsers. If getItem cannot be found, the value is NULL

18.1 storage localStorage

Storage: localstorage setItem(“key”, “value”);

Remove: localstorage getItem(“key”);

Delete: localstorage removeItem(“key”);

Empty: localstorage clear()

// Example: after the user logs in successfully, save the token returned by the back end and request the user information on the home page
// The login page stores the token and id
localStorage.setItem('token',res.token)
// Get the token and id on the homepage
const token = localStorage.getItem('token')
const id = localStorage.getItem('id')
// Send request to get user information
$.ajax({
    url:'http://localhost:8888/test'
    method:'GET',
    data:{id:id}
    headers:{
		authorization:token    // Request header
	},
    success(res){
    	console.log(res)
	}
})

18.2 storage sessionStorage

Storage: sessionstorage setItem(“key”, “value”);

Remove: sessionstorage getItem(“key”);

Sessionstorage: delete removeItem(“key”);

Empty: sessionstorage clear()

difference:

localStorage closes the browser and is still there unless you delete or empty the browser cache yourself

sessionStorage closes and the browser empties

19.Const constant change

  1. The variables of "basic data type" defined by const cannot be modified

  2. The "reference data type" defined by const is OK!

Conclusion: watch videos and take notes to form a good habit

Keywords: Javascript Front-end html css

Added by dujed on Thu, 03 Mar 2022 09:27:14 +0200