使用JS中的循环构建HTML



下午好,我正试图通过一个循环在JS中构建一些HTML元素,在这个循环中我有另一个循环。我已经编写了HTML,所以我知道我想要什么,所以我现在尝试将它翻译成JS。

我想要构建的HTML(这将是一个3x3网格(:

<div class="grid">
<div class="square-row d-flex flex-row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="square-row d-flex flex-row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="square-row d-flex flex-row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
</div>

我写的JS代码(很抱歉格式不好(我的第一篇Stackoverflow帖子,我无法让它正常运行(:

function generateGrid(requirement) {
let grid = `
<div class="grid">
`;
if (requirement) {
for (let i = 0; i < gridSize; i++) {
let gridRow = `
<div class="square-row d-flex flex-row">
`;
for (let s = 0; s < gridSize; s++) {
let square = `
<div class="square squares" id="${i}"></div>
`;
gridRow += square;
}
gridRow +=`
</div>
`;
}
} else {
for (let i = 0; i < gridSize; i++) {
let gridRow = `
<div class="square-row d-flex flex-row">
`;
for (let x = 0; x < gridSize; x++) {
let square =`
<div class="square squares" id="square${i}" onclick="addColour(${i})"></div>
`;
gridRow += square;
}
gridRow +=`
</div>
`;
}
}
grid += `
</div>
`;
return grid;
}

当我运行它时,我最终得到了这个:

<div class="grid">
</div>

我在循环的中间使用了关键字"debugger",它正在循环中移动。gridSize的值为3,因此外部循环应该运行三次,内部循环也应该在每次运行外部循环时运行三次。

如有任何帮助或建议,我们将不胜感激。

我不能100%确定你的确切意思,但你的问题似乎是一个简单的错误,忘记将gridRow添加到网格中。

let gridSize = 3
function generateGrid(requirement) {
let grid = `<div class="grid">n`;
if (requirement) {
for (let i = 0; i < gridSize; i++) {
let gridRow = `t<div class="square-row d-flex flex-row">n`;
for (let s = 0; s < gridSize; s++) {
let square = `tt<div class="square squares" id="square${i}" onclick="addColour(${i})"></div>n`
if (requirement) {
square = `tt<div class="square squares" id="${i}"></div>n`;
}
gridRow += square;
}
gridRow += `t</div>n`;
grid += gridRow; // this line
}
}
grid += `</div>n`;
return grid;
}
console.log(generateGrid(true))

相关内容

  • 没有找到相关文章

最新更新