HTML更新但不可视更新

时间:2018-10-14 15:52:13

标签: javascript html

我正在开发包含JavaScript的HTML游戏。 ID为status的元素包含Current Turn: <span id="player">Player 1</span>。我使用以下代码切换播放器。

if(player === 1) {
    player = 2;

    playerLabel.innerHTML = "Player 2"
    playerLabel.style.color = "blue";
}else {
    player = 1;

    playerLabel.innerHTML = "Player 1"
    playerLabel.style.color = "red";
}

一切正常,直到我必须使用以下代码重置游戏。

player = 1;
marked = 0;
selectedRow = undefined;
win = false;

marks = [
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
    {isMarked: false},
];

statusLabel.innerHTML = "Current Turn: <span id=\"player\">Player 1</span>";
statusLabel.style.color = "black";
playerLabel.style.color = "red";
playerLabel.innerHTML = `Player 1`;

doneButton.style.backgroundColor = "grey";
doneButton.innerHTML = "You Must Mark At Least One Line";

for (var i = 0; i < gameButton.length; i++) {
    gameButton[i].classList.remove("red");
}

当游戏重置并且当您转弯时,玩家标签永远不会更新,尽管它说如果我在控制台中记录该元素也会这么做。

  • gameButton是所有标记。
  • doneButton是切换匝数的按钮。

1 个答案:

答案 0 :(得分:0)

我不知道代码中的playerLabel变量在哪里,但是我很确定您是在游戏的初始阶段以及在进行statusLabel.innerHTML = "Current Turn: <span id=\"player\">Player 1</span>";时创建它的您正在创建一个新的<span>元素,与之前的playerLabel不同。

因此,在statusLabel.style.color = "black";之后,尝试用playerLabel或您使用的任何功能重新分配getElementById()