【问题标题】:I got an 'Reference Error: button is not defined' error我收到“参考错误:未定义按钮”错误
【发布时间】:2020-06-03 04:19:44
【问题描述】:

目前正在学习“什么是闭包”并尝试此练习代码。在 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

【问题讨论】:

  • never read 表示您尚未在代码中的任何位置使用 Button
  • ReferenceError: buttons is not defined 那么,你在哪里定义了buttons? (听起来你没有)
  • 哦,我很愚蠢..谢谢

标签: javascript node.js reactjs ecmascript-6


【解决方案1】:
//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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2023-03-14
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多