我想在单元格中添加一个id,所以就像第0行/第0列的id为1,第0行/第1列的id为2,等等。
继承我正在使用的代码:
function init() {
var board = document.getElementById("board");
var NUM_ROWS = 6;
var NUM_COLS = 6;
for (row = 0; row < NUM_ROWS; row++) {
var tr = document.createElement("tr");
for (col = 0; col < NUM_COLS; col++) {
var td = document.createElement("td");
var img = document.createElement("img");
img.src = 'images/image0.png';
img.id = 'r' + row + 'c' + col;
td.appendChild(img);
td.addEventListener("click", function() {
var img = this.childNodes[0];
img.src = 'images/image1.png';
});
tr.appendChild(td);
}
board.appendChild(tr);
}
答案 0 :(得分:0)
您可以创建和增加id
变量,为每个表格单元格分配一个有序的数字标识符:
var board = document.getElementById("board");
var NUM_ROWS = 6;
var NUM_COLS = 6;
var id = 1;
for (row = 0; row < NUM_ROWS; row++) {
var tr = document.createElement("tr");
for (col = 0; col < NUM_COLS; col++) {
var td = document.createElement("td");
td.id = id++;
var img = document.createElement("img");
img.src = 'images/image0.png';
img.id = 'r' + row + 'c' + col;
td.appendChild(img);
td.addEventListener("click", function() {
var img = this.childNodes[0];
// showPicture(img);
console.log(img.id);
});
tr.appendChild(td);
}
board.appendChild(tr);
}
<table id="board"></table>