[英]I got an 'Reference Error: button is not defined' error
目前正在學習“什么是閉包”並嘗試此練習代碼。 在Visual Studio 代碼中運行。
for (let [idx,btn] of buttons.entries()) {
btn.addEventListener(
"click",
function onClick(){
console.log(
`Clicked on button (${ idx })!
`);
}
);
}
預計每次迭代都會獲得新的塊范圍(idx,btn)變量; 並且期望循環每次都會創建一個新的內部 onClick(..) 函數。但是它得到了這個錯誤。
PS C:\Users\leePC\babel\public\src> node test.js
C:\Users\leePC\babel\public\src\test.js:1
for (let [idx,btn] of buttons.entries()) {
btn.addEventListener("click",function onClick(){
console.log(`Clicked on button (${ idx })!`); }); }
^
ReferenceError: buttons is not defined
at Object.<anonymous>
(C:\Users\leePC\babel\public\src\test.js:1:31)
at Module._compile
(internal/modules/cjs/loader.js:1157:30)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1177:10)
at Module.load (internal/modules/cjs/loader.js:1001:32)
at Function.Module._load
(internal/modules/cjs/loader.js:900:14)
at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
既然有人說我應該實施
npm install react-uikit-button --save;
// ES6
import Button from 'react-uikit-button';
// ES5
var Button = require('react-uikit-button');
並嘗試在代碼前面導入,但還是不行。 它彈出不同的錯誤......如何解決這個問題?
編輯:當我使用 import 語句然后通過 Babel 轉換此代碼時,發生了此錯誤。(在 Visual Studio 代碼中)
'Button' is declared but its value is never read
//May be the scope of buttons does not exists.
//Try to run this one.
<!DOCTYPE html> <html> <head> <script> function myFunction() { let buttons = document.querySelectorAll(`[id]`) for (let [idx, btn] of buttons.entries()) { btn.addEventListener("click", function onClick() { alert(`Clicked on button (${idx})! `); }); } } </script> </head> <body onload="myFunction()"> <button id="0"> 0 </button> <button id="1"> 1 </button> <button id="2"> 2 </button> <button id="3"> 3 </button> <button id="4"> 4 </button> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.