1. 程式人生 > >js中常見面試問題-筆記

js中常見面試問題-筆記

doc 重新 amp 原理 parent 事件 del 結果 ear


原文參考https://mp.weixin.qq.com/s/mCVL6qI33XeTg4YGIKt-JQ

1.事件代理
給父元素添加事件,利用事件冒泡原理,在根據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.在循環中使用閉包
var arr = [1,2,3,4,5];
for(var i=0; i<arr.length; i++){
setTimeout(function(){
console.log(i)
},1000)
}
輸出結果為:5,5,5,5,5
想要讓i輸出0,1,2,3,4
方法一使用閉包
for(var i=0; i<arr.length; i++){
setTimeout(function(j){// 這裏將值傳入
console.log(j)// 這裏接受
}(i),1000)// 閉包的使用
}
方法二let關鍵字
for(let i=0; i<arr.length; i++){
setTimout(function(){
console.log(i)
},1000)
}
3.滾動頁面和窗口調整時,觸發事件。
核心思想利用setTimeout延遲功能,來處理事件。
// 參數一接受執行函數,參數二延遲時間
function debounce(fn,delay){
// 維護一個timer
let timer = null;
// 能訪問timer的閉包
return function(){
// 通過this和arguments獲取函數的作用域和變量
let context = this;
let args = arguments;
// 如果事件被調用,清除timer然後重新設置timer
clearTimeout(timer);
timer = setTimeout(function(){
fn.apply(context,args);
},delay);
}
}

js中常見面試問題-筆記