我的 html 中有一个代表棋盘的表格,代码如下:
<table id="chess-board" class="board">
{% for row in range(8) %}
<tr>
{% for col in range(8) %}
<td id="{{ 'ABCDEFGH'[col] }}{{ 1+row }}" onclick="handleClick('{{ 'ABCDEFGH'[col] }}{{ 1+row }}')">{{ 'ABCDEFGH'[col] }}{{ 1+row }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
我想访问表的字段,并用 js 中每个函数的片段填充它:
function renderBoard(gameState) {
const chessBoard = document.getElementById("chess-board");
chessBoard.innerHTML = ''; // Clear the board before re-rendering
// Loop through the rows of the board (gameState.board is an 8x8 array)
Object.entries(gameState.board).forEach(([key, pieceData]) => {
const [rowIndex, colIndex] = key.split(',').map(Number);
const squareId = `${'ABCDEFGH'[colIndex]}${1 + rowIndex}`; // Calculate the cell ID (e.g., A1, B2, ...)
const cellElement = document.getElementById(squareId); // Get the corresponding <td> element
console.log(cellElement)
if (cellElement) {
// If there is a piece in this square, add it
if (pieceData && pieceData.type !== null) {
const pieceImage = document.createElement("img");
// Set the piece image based on the type and color
const pieceType = pieceData.type;
pieceImage.src = `static/pieces/${pieceType}.png`;
pieceImage.alt = `${pieceData.color} ${pieceType}`;
pieceImage.classList.add("piece"); // Optional: add CSS class to style the pieces
// Clear any existing piece (in case the square was previously occupied)
cellElement.innerHTML = ''; // Clear previous content
// Append the new piece image to the <td> element
cellElement.appendChild(pieceImage);
} else {
// If there is no piece, make sure the <td> is empty
cellElement.innerHTML = '';
}
} else {
console.log(`Error: Could not find element with ID: ${squareId}`);
}
});
}
squareId 计算正确,但随后 cellElement 变为 null,我不明白为什么
我尝试通过手动放置每个 tr 和 td 以及所有 Id 来实现没有循环的 html 棋盘,以便它们 100% 正确,但仍然不起作用
我尝试使用 #A1 等访问 css 中 tds 的 id。这很有效,所以我知道 id 是正确给出的。
我尝试在 DOMContentLoades 之后以及 window.onload 之后调用函数,但都没有解决问题。
谢谢您的帮助!
不知道 gameState 板应该是什么样子,但我看到你正在调用 split on key 而不是pieceData。 无论如何,在 FireFox 等浏览器中使用单独的 js 文件设置断点并查看与控制台日志相比在哪里获取 null 可能更容易。