如何用JavaScript为多个同ID的div添加子div?嵌套井字棋实现疑问
嵌套式井字棋页面结构构建问题解决方案
问题描述
我正在用HTML/JavaScript开发嵌套式井字棋游戏,每个大棋盘的格子对应一个小井字棋,希望通过JS构建页面结构,但目前无法将创建div的函数应用到多个div上。
现有代码
function create_elements_from_html(n, html){ const template = document.createElement("template") let htmlaux = `` for (a = 0; a < n; a += 1){ htmlaux += html } template.innerHTML = htmlaux return template.content; } let big_board = create_elements_from_html(1, `<div id="big_board">big</div>`) document.body.appendChild(big_board) let small_board = create_elements_from_html(9, `<div id="small_board">small</div>`) document.getElementById("big_board").appendChild(small_board) let cell = create_elements_from_html(9, `<div id="cell">cell</div>`) document.getElementById("small_board").appendChild(cell)
期望生成结构(含9个小棋盘,每个小棋盘带9个格子)
<div id="big_board"> big <div class="small_board"> small <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> <div class="cell"> cell</div> </div> <!-- 剩余8个相同结构的small_board --> </div>
问题分析
- ID重复违规:HTML要求ID全局唯一,循环生成多个
id="small_board"和id="cell"后,document.getElementById只能找到第一个匹配元素,导致后续小棋盘无法添加格子。 - 逻辑遗漏:当前代码仅给第一个小棋盘添加了格子,其余8个小棋盘未做处理。
修正后的代码
function create_elements_from_html(n, html){ const template = document.createElement("template") let htmlaux = `` for (let a = 0; a < n; a += 1){ // 用let声明循环变量,避免全局污染 htmlaux += html } template.innerHTML = htmlaux return template.content; } // 创建大棋盘 let big_board = create_elements_from_html(1, `<div id="big_board">big</div>`) document.body.appendChild(big_board) const bigBoardEl = document.getElementById("big_board") // 循环创建9个小棋盘,每个小棋盘添加9个格子 for(let i = 0; i < 9; i++){ // 创建单个小棋盘容器 const smallBoard = document.createElement("div") smallBoard.className = "small_board" smallBoard.textContent = "small" // 生成9个格子并添加到当前小棋盘 const cells = create_elements_from_html(9, `<div class="cell">cell</div>`) smallBoard.appendChild(cells) // 将小棋盘加入大棋盘 bigBoardEl.appendChild(smallBoard) }
关键改动说明
- 把重复的
id替换为class,符合HTML规范,也便于后续批量操作元素。 - 新增循环逻辑,逐个创建小棋盘并为每个小棋盘单独添加格子,确保所有小棋盘都有完整的单元格结构。
- 给循环变量添加
let声明,避免全局变量污染问题。
内容的提问来源于stack exchange,提问作者Pudimedo
相关产品推荐
相关产品推荐

