CVTE面試題——解決用addEventListener繫結的函式傳參無效問題
阿新 • • 發佈:2019-02-09
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input id="content" value="輸入內容" /> </body> <script> var oInput = document.getElementById("content"); oInput.addEventListener("keyup",deBounce(fn,2000),false) function fn(){ console.log(this.value); }; function deBounce(delay){ return fn } </script> </html>
<!--問題 : 在輸入框內每次鍵盤輸入內容時,訪問後臺比較耗費效能 需求 : 使用者連續輸入時不請求 , 按鍵擡起兩秒內無內容輸入時再請求 , 改造deBounce函式-->
今天去CVTE面試,面試官給了這樣一道題,當時除錯的時候就懵逼了,在deBounce裡打的斷點根本無效 , 寫的程式碼沒有生效。原來js的addEventListener繫結匿名函式時是沒有問題的,但是要給函式傳參的話下邊這種寫法是有問題的
deBounce(fn,2000)
如果要傳參,要用deBounce.bind(fn,2000),以下是改造後的程式碼。心塞,這種情況問題頭回遇到,權當學習了把!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input id="content" value="輸入內容" /> </body> <script> var oInput= document.getElementById("content"); oInput.addEventListener("keyup",deBounce.bind(fn,2000),false) function fn(){ console.log(this.value); }; function deBounce(delay){ var value = oInput.value clearTimeout(this.timer); //關閉已開的定時器 this.timer = setTimeout(function(){ clearTimeout(this.timer); //關閉已開的定時器 console.log(value) },delay) } </script> </html>