我正在用javascript制作生活中的conways游戏,但无法让我的onclick实现起作用。单击td时应该更改单元格的寿命状态,但是相反,我在控制台上看到一条错误消息:TypeError:World.tds未定义。
TLDR:无法弄清楚为什么onclick无法使用。由于某些原因,未定义World.tds []。

Onclick实施:

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);

10-08 15:14