0

我正在尝试制作一个简单的战舰游戏,其中一张 10x10 的桌子用作比赛场地。我希望能够轻松更改船长和船数,这就是我(尝试)针对 HTML 对象(表格单元格)存储信息的原因。该表具有每个单元格的唯一 ID,写为 cell_3_8。

我的问题是如何使用自定义属性,在这种情况下,hasBoat 以存储和更改有关单元格的信息。我已将每个单元格设置为在开始时将属性 hasBoat 设置为 0,并在我希望将船放置在那里时将值设置为 1。目前,当我尝试放置船只时,桌子上没有发生任何事情,并且在 Chrome 控制台中检查时,它显示“Uncaught TypeError: Cannot set property 'hasBoat' of null”。

如果你能解释这里的问题是什么,甚至更好的是如何解决它,那就太好了。这是代码:

var boatCell
var boatNum;
var boatLen
var boatPos;

function getCoordinate() {

    for (boatNum = 1; boatNum < 4; boatNum++) {
        for (boatLen = 1; boatLen < 4; boatLen++) {
            var x = Math.floor(Math.random() * 10);
            var y = Math.floor(Math.random() * 10 + 1);
            x = x++;
            boatPos = "cell_" + "_" + x + "_" + y;
            boatCell = document.getElementById(boatPos);
            boatCell.hasBoat = 1;
        }
            if (boatCell.hasBoat == 1) {
                boatCell.style.backgroundColor = "brown";
            }
    }
}
4

2 回答 2

1

你的问题是因为你没有一个元素 id = "cell_" + "" + x + "" + y; 和boatCell = document.getElementById(boatPos); 将变量boatCell 的值设置为 null,请参见示例

var exist = document.getElementById("cell_1_4");
console.log(exist);

var notExist = document.getElementById("cell_1_3");
console.log(notExist);
<div id="cell_1_4"></div>

于 2016-06-03T00:26:08.407 回答
0

您得到的错误与设置hasBoat属性无关。相反,就是boatCell这样null。我相信你的意思是拥有ifinner for,如下所示:

for (boatNum = 1; boatNum < 4; boatNum++) {
    for (boatLen = 1; boatLen < 4; boatLen++) {
        var x = Math.floor(Math.random() * 10);
        var y = Math.floor(Math.random() * 10 + 1);
        x = x++;
        boatPos = "cell_" + "_" + x + "_" + y;
        boatCell = document.getElementById(boatPos);
        boatCell.hasBoat = 1;

        if (boatCell.hasBoat == 1) {
            boatCell.style.backgroundColor = "brown";
        }
    }
}
于 2016-06-03T00:27:16.813 回答