首先,这是我的代码。

    var p1 = document.querySelector(".playerOne");
    var p2 = document.querySelector(".playerTwo");
    var p1Display = document.querySelector("#p1Span");
    var p2Display = document.querySelector("#p2Span");
    var header = document.querySelector("h1");
    var reset = document.querySelector(".reset");
    //var input = document.getElementsByTagName("input");
    var until = document.getElementsByClassName(".until");
    var p1Score = 0;
    var p2Score = 0;
    var gameOver = false;
    var max = 5;

    p1.addEventListener("click", function() {
        if (!gameOver) {
            p1Score++;
            p1Display.textContent = p1Score;
            header.textContent = (p1Score + " to " + p2Score);
        }
        if (p1Score === max) {
            p1Display.classList.add("winner");
            gameOver = true;
        }
    });
    p2.addEventListener("click", function() {
        if (!gameOver) {
            p2Score++;
            p2Display.textContent = p2Score;
            header.textContent = (p1Score + " to " + p2Score);
        }
        if (p2Score === max) {
            p2Display.classList.add("winner");
            gameOver = true;
        }
    });
    reset.addEventListener("click", function() {
        gameOver = false;
        p1Score = 0;
        p2Score = 0;
        p1Display.classList.remove("winner");
        p2Display.classList.remove("winner");
        header.textContent = (p1Score + " to " + p2Score);
    });
    .winner {
        color: green;
    }
    <html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>JS practice 2</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <h1><span id="p1Span">0</span> to <span id="p2Span">0</span></h1>
        <p class="until">Playing to: </p>
        <input type="number">
        <button class="playerOne">Player One</button>
        <button class="playerTwo">Player Two</button>
        <button class="reset">Reset</button>
        <script type="text/javascript" src="main.js"></script>

    </body>
    </html>


因此,如您所见,我的p1Display和p2Display应该变成绿色。
问题是,他们没有这样做,而他们却以5分的速度选出了类(class)冠军。为什么当它具有将其变成绿色的类时却没有变成绿色?

最佳答案

您必须在所有功能中删除此代码:

header.textContent =(p1Score +“到” + p2Score);

另外,您应该从重置功能中删除同一行,并更新p1Display.textContent和p2Display.textContent以使该功能正常工作。

reset.addEventListener("click", function () {
    gameOver = false;
    p1Score = 0;
    p2Score = 0;

    p1Display.textContent = p1Score;
    p2Display.textContent = p2Score;

    p1Display.classList.remove("winner");
    p2Display.classList.remove("winner");
    //header.textContent = (p1Score + " to " + p2Score);
});

问候!

10-04 21:25