我使用表格创建了一个棋盘。我想检索单元格的 x 和 y 坐标。但是,this.parentNode.rowIndex
一直给我-1。我花了无数个小时寻找错误。谁能帮我找到它?
var board = [[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, -1, 0, -1, 0, -1, 0, -1],
[-1, 0, -1, 0, -1, 0, -1, 0],
[0, -1, 0, -1, 0, -1, 0, -1]];
var gray = -1; //distinguishing players
var red = 1;
function makeBoard() {
//create a table
var tbl = document.createElement("table");
//create a <tr> for each row
for (var i = 0; i < 8; i++) {
var tr = document.createElement("tr");
//create a <td> for each column
for (var j = 0; j < 8; j++) {
var td = document.createElement("td");
//setting the attributes of a square
td.setAttribute("width", "50");
td.setAttribute("height", "50");
if ((i % 2 == 0 && j % 2 != 0) || (i % 2 !=0 && j % 2 == 0)) {
td.style.backgroundColor = "black";
}
else if (board[i][j] == red) {
td.style.backgroundColor = "red";
}
else if (board[i][j] == gray) {
td.style.backgroundColor = "gray";
}
td.onclick = function() {
alert(this.cellIndex + ", " + this.parentNode.rowIndex); //RETRIEVING WRONG COORDINATES
}
tr.appendChild(td);
}
tbl.appendChild(tr);
}
tbl.setAttribute("border", "10");
return tbl;
}
如果您觉得缺少什么,请告诉我。