正在更改<td>点击javascript

Changing status of <td> on click with javascript

本文关键字:td 点击 javascript gt lt      更新时间:2023-09-26

我正在用javascript制作一个人生的康威游戏,但我的onclick实现无法正常工作。本应在单击td时更改单元格的生存状态,但我在控制台上收到一个错误,显示:TypeError:World.tds未定义。TLDR:不明白为什么onclick不起作用。由于某种原因,World.tds[]未定义。

点击实现:

if (table !== null) {
for (var i = 0; i < 20; i++) {
    for (var j = 0; j < 20; j++)
        World.tds[i][j].onclick = function() {
            if (World.tds[i][j].cells.alive) {
                World.tds[i][j].cells.alive = false;
            } else {
                World.tds[i][j].cells.alive = true;
            }
        };
}
}

构造函数和tds[]填充

var World = function() {
this.h = maxH;
this.w = maxW;
this.tds = [];
};
//generate the world in which the cells move
World.prototype.init = function() {
var row, cell;
for (var r = 0; r < this.h; r++) {
    this.tds[r] = [];
    row = document.createElement('tr');
    for (var c = 0; c < this.w; c++) {
        cell = document.createElement('td');
        this.tds[r][c] = cell;
        row.appendChild(cell);
    }
    table.appendChild(row);
}
};

问题语句-当您触发点击处理程序时,到那时,i和j的值已分别更新为20,并且World.tds[20][20]未定义。

for loop中的代码更新为

(function(i,j) {
        World.tds[i][j].onclick = function() {
            if (World.tds[i][j].cells.alive) {
                World.tds[i][j].cells.alive = false;
            } else {
                World.tds[i][j].cells.alive = true;
            }
        };
})(i,j);