首页 > 解决方案 > 重新运行函数时应用了错误的 CSS 类

问题描述

我正在开发一个点击式游戏,其中向用户呈现坐标,然后他们必须单击相应的坐标。

我已经对其进行了样式设置,如果它们是正确的,则会添加一个在其分数周围放置绿色边框的类。如果他们不正确,则会添加一个不同的班级,这会在他们的分数周围加上一个红色边框。这在第一次玩游戏时有效。问题是每次播放它只应用红色边框,无论它是否正确。

我很困惑,因为它仍然正确计算分数 - 如果您单击正确的方块,那么您仍然会得分,但它应用了错误的类。

这是我的 codepen 的链接:https ://codepen.io/jacobc1596/pen/yLNwQZR

这是我认为的相关代码:

function startGame() {

    board.style.pointerEvents = 'all';
    target.innerHTML = randomSquare;
    gameTime()

    document.querySelectorAll('.square').forEach(item => {
        item.addEventListener('click', event => {
            if(item.id == randomSquare) {
                score++
                tries++
                scoreOutput.innerHTML = score;
                randomSquare = rndSq(squareset);
                target.innerHTML = randomSquare;
                scoreOutput.classList.add('correct'); //adds 'correct' class
                scoreOutput.classList.remove('incorrect'); //removes 'incorrect' class
            } else {
                tries++;
                // scoreDisplay.innerHTML = score;
                randomSquare = rndSq(squareset);
                target.innerHTML = randomSquare;
                scoreOutput.classList.remove('correct'); //removes 'correct' class
                scoreOutput.classList.add('incorrect'); //adds 'incorrect' class
            };
        })
    })
};

//Reset Game (runs when the game timer runs out)
function reset() {
    tries=0;
    score=0;
    target.innerHTML = '';
    strt.style.visibility = "visible";
    rst.style.visibility = 'hidden';
    board.style.pointerEvents = 'none'; 

    //to remove whatever class was last applied before game finish.
    scoreOutput.classList.remove('incorrect');
    scoreOutput.classList.remove('correct');
    scoreOutput.innerHTML = '';
}

//End Game
function end() {
    scoreDisplay.innerHTML = "Time's Up! You scored " + score + " points!"
    reset();
}
.correct {
    border:6px solid green;
    border-radius: 50%;
}

.incorrect {
    border:6px solid red;
    border-radius: 50%;
}

标签: javascripthtmlcss

解决方案


每次开始游戏时,都会向所有方块添加事件侦听器:

function startGame() {

board.style.pointerEvents = 'all';
target.innerHTML = randomSquare;
gameTime()

document.querySelectorAll('.square').forEach(item => {
    item.addEventListener('click', event => {     //////   <<<<  HERE

第二次运行游戏时,点击的方块中有 2 个监听器。

第一个运行正常,正如预期的那样。但是会改变 randomSquare 值。

第二个事件会报失败,因为现在点击的方块不再是randomSquare

当您运行游戏 100 次时,您有 6400 名听众!!!!


推荐阅读