同时检查用户输入。然而,控制台给我一个错误,说“大小没有定义”,我认为是因为大小在函数内,而while条件在函数之外
const newGrid = document.getElementById('new-grid');
newGrid.addEventListener('click', createGrid);
const main = document.querySelector('main');
function createGrid() {
do {
let size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);
const numPx = (600 / size) - 2;
let px = numPx + 'px';
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
const div = document.createElement('div');
div.setAttribute('class', 'grid');
main.appendChild(div);
div.setAttribute('style', `width: ${px}; height: ${px}`);
}
}
} while(isNaN(size) || size > 64 || size < 1);
}
答案 0 :(得分:3)
您可以在函数内但在let size;
块之外声明变量(do
),然后在size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);
块中分配它(do
)。
答案 1 :(得分:0)
您的选择是:
更优雅 - 将let size
更改为const size
(因为您无需重新分配)并将其升级为如下所示:
function createGrid() {
const size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);