Original reference Https://mp.weixin.qq.com/s/mCVL6qI33XeTg4YGIKt-JQ
1. Event Broker
Adds an event to the parent element, using the event bubbling principle, to get child elements based on E.target
<ul id= "Parentbox" >
<li class= "Item" >1</li>
<li class= "Item" >2</li>
<li class= "Item" >3</li>
</ul>
Let Parentbox = document.getElementById (' Parentbox ');
Parentbox.addeventlistener (' click ', Function (e) {
if (e.target && e.target.nodename = = = ' LI ') {
Let item = E.target;
Console.log (item);
}
})
2. Using closures in loops
var arr = [1,2,3,4,5];
for (var i=0; i<arr.length; i++) {
SetTimeout (function () {
Console.log (i)
},1000)
}
The output is: 5,5,5,5,5
Want to let I output 0,1,2,3,4
Method one using closures
for (var i=0; i<arr.length; i++) {
SetTimeout (function (j) {//Here the value is passed in
Console.log (j)//Accept Here
} (i), 1000)//use of closures
}
Method two let keyword
for (let i=0; i<arr.length; i++) {
Settimout (function () {
Console.log (i)
},1000)
}
3. When scrolling the page and window adjustment, the event is triggered.
The core idea is to use the settimeout delay function to handle events.
Parameter one accepts execution function, parameter two delay time
function Debounce (fn,delay) {
Maintain a timer
let timer = null;
A closure that can access the timer
return function () {
Get the scope and variables of a function through this and arguments
let context = this;
let args = arguments;
If the event is called, clear the timer and then reset the timer
Cleartimeout (timer);
Timer = setTimeout (function () {
Fn.apply (Context,args);
},delay);
}
}
Common interview Questions in JS-notes