【问题标题】:Console error saying variable not defined, even though defined in same function控制台错误提示变量未定义,即使在同一函数中定义
【发布时间】:2022-01-02 18:21:37
【问题描述】:

我有一个名为 grid 的变量,其中包含名为 elements 的变量。

单击按钮时,我想删除网格并将其替换为新网格。这是通过事件侦听器、函数和 if 语句完成的。

但是我收到一个控制台错误,告诉我“网格未定义”。

谁能帮忙?

//Create preset variables
let body = document.querySelector('body');
let content = document.querySelector('.content');
let numberOfSquares = 16;
let randomColorValue = '';
let colorShade = 10;
let buttonClicks = 0;
/* let grid = document.createElement('div'); */

//Create variable called container that contains a div
let container = document.createElement('div');
container.classList.add('container');
body.appendChild(container);

// Add a button &  position to top of screen
let button = document.createElement('button');
button.textContent = "Refresh!";
button.classList.add('refresh-button');
content.appendChild(button);
button.addEventListener('click', refreshGrid);

squaresInGrid();

function squaresInGrid() {
    if (buttonClicks > 0) {
        console.log(buttonClicks);
        container.removeChild(grid);
    }

    for (i = 0; i < numberOfSquares; ++i) {
        let grid = document.createElement('div');
        grid.classList.add('grid');
        container.appendChild(grid);

         let element = document.createElement('div');
         element.classList.add('grid-item');
         element.addEventListener('mouseenter', function mouseEnterFunctions() {
             randomColor();
             hoverStyle();
            --colorShade;
            element.removeEventListener('mouseenter', mouseEnterFunctions);
         });

        function hoverStyle() {
            element.style.backgroundColor = '#'+randomColorValue;
            element.style.opacity = (colorShade / 10); 
        }

        function randomColor() {
            randomColorValue = Math.floor(Math.random()*16777215).toString(16);
        }

        grid.appendChild(element);                
    }
} 

//Function to be called on button click removing existing grid and replacing with a new one
function refreshGrid() {
    ++buttonClicks;
    numberOfSquares = prompt("How many squares would you like? (Maximum 100)");
    colorShade = 0;
    squaresInGrid();
}

【问题讨论】:

  • 错误是否告诉您它发生在哪一行?
  • 您能否详细说明您希望如何在randomColor() 函数的范围内定义grid...?
  • 谢谢它说“133:27 未捕获的ReferenceError:未定义网格”我正在使用JSFiddle。 jsfiddle.net/stcLg6dn/7@HanchenJiang
  • @esqew 对不起,我不明白你的问题。我是编码新手。
  • 您在 for 循环中定义了 grid,在 if () 语句中的 squaresInGrid 函数顶部无法访问它。

标签: javascript loops if-statement


【解决方案1】:

您在 for 循环中定义了 grid 变量,因此只能在循环内部访问它。

您应该取消注释代码顶部的行,使其成为全局变量。然后在 for 循环中,删除网格变量前面的 let 关键字,以便它始终引用外部变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多