有不同的方法可以实现我认为你想要的。随时更新您的问题以反映您的意愿。按照评论中的要求添加您的 HTML 会很有用。
让我们假设您的表不使用 rowspan 或 colspan。像这样的东西:
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
有两个循环的基本方式:
// Lets get all your rows
var rows = document.querySelectorAll("table tr");
// for each row...
for (var j = 0; j < rows.length; j++) {
var row = rows[j];
// ... we will find all this rows' cells.
var cells = row.querySelectorAll("td");
// for each cell...
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
// ... we will set its textContent to its coordinate in the table
cell.textContent = "X: " + (i + 1) + " / Y: " + (j + 1);
}
}
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
如果您事先知道列数,则另一种解决方案:
var colsCount = document.querySelectorAll("table tr:nth-child(1) td").length;
var cells = document.querySelectorAll("table td");
for (var i = 0; i < cells.length; i++) {
const y = i / colsCount | 0;
const x = i % colsCount;
cells[i].textContent = `X: ${x + 1} / Y: ${y + 1}`;
}
<table border="1">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>