战舰游戏开发:如何用X/Y坐标动态更新HTMLCollection?
解决方案
方法1:计算一维索引
由于棋盘是固定的10x10规格,可通过公式将二维坐标转换为一维索引,直接访问HTMLCollection中的元素:
const displayCompAttk = () => { const result = game.computer.sendAttack(game.player) const x = result[0] const y = result[1] // 10列的棋盘,索引 = 行号*10 + 列号 const index = x * 10 + y playerCells[index].textContent = result[2] }
方法2:通过元素属性定位
创建单元格时已为每个元素添加了x和y属性,可利用属性选择器精准查找目标元素:
const displayCompAttk = () => { const result = game.computer.sendAttack(game.player) const x = result[0] const y = result[1] // 组合属性选择器定位单元格 const targetCell = document.querySelector(`.p-board-cell[x="${x}"][y="${y}"]`) targetCell.textContent = result[2] }
方法3:提前维护二维映射数组
在创建棋盘时,同步将单元格元素存入一个二维数组,后续直接通过坐标访问,避免重复计算或查找:
- 新增全局二维数组存储单元格引用:
// 存储玩家棋盘的二维单元格引用 const playerBoardCells = []
- 修改
createPlayerDisplay函数,将生成的单元格存入数组:
const createPlayerDisplay = () => { const board = game.player.playerGameboard.getBoard() for (let i = 0; i < board.length; i += 1) { playerBoardCells[i] = [] // 初始化当前行的数组 board[i] = [] for (let j = 0; j < board.length; j += 1) { const cell = document.createElement("td") cell.classList.add("p-board-cell") cell.setAttribute("x", i) cell.setAttribute("y", j) board[i][j] = cell playerBoardCells[i][j] = cell // 存入二维数组 } } // 行创建与插入逻辑保持不变 for (let i = 0; i < 10; i += 1) { const row = document.createElement("tr") for (let j = 0; j < 10; j += 1) { row.append(board[i][j]) } row.classList.add("p-board-row") playerContainer.append(row) } }
- 修改
displayCompAttk函数直接访问二维数组:
const displayCompAttk = () => { const result = game.computer.sendAttack(game.player) const x = result[0] const y = result[1] playerBoardCells[x][y].textContent = result[2] }
内容的提问来源于stack exchange,提问作者DataMoshing
相关产品推荐
相关产品推荐

