按钮改变颜色,即使它已经被分配

button changes color even if it's already assigned

我有这个问题:每当我点击 div,我想添加背景颜色。永远。但即使我点击更多(如循环),背景也会发生变化。如何设置永远的背景色?

const blocks = document.querySelectorAll('.game div');
const liveNumber = document.querySelector('.lives-num');
let lives = 1;


function letTheGameBegin(e, r) {
    const rand = Math.floor(Math.random() * 100);
    if (rand < 40) {
        e.target.style.backgroundColor = 'green';
    } else if (rand < 60) {
        e.target.style.backgroundColor = 'yellow';
        lives++;
    } else if (rand < 90) {
        e.target.style.backgroundColor = 'red';
        lives--;
    } else {
        e.target.style.backgroundColor = 'white';
    }
    liveNumber.innerHTML = lives;
    if (lives === 0) {
        //document.querySelector('.game-over').style.display = 'flex';
    }
}

blocks.forEach(block => block.addEventListener('click', letTheGameBegin));

我想你的意思是你只想 运行 每个 div JS 一次。

试试这个例子,看看它是否是你需要的:jsfiddle

function letTheGameBegin(e, r) {
    const rand = Math.floor(Math.random() * 100);
    if(!e.target.style.backgroundColor){
        if (rand < 40) {
            e.target.style.backgroundColor = 'green';
        } else if (rand < 60) {
            e.target.style.backgroundColor = 'yellow';
            lives++;
        } else if (rand < 90) {
            e.target.style.backgroundColor = 'red';
            lives--;
        } else {
            e.target.style.backgroundColor = 'white';
        }
        liveNumber.innerHTML = lives;
        if (lives === 0) {
            //document.querySelector('.game-over').style.display = 'flex';
        }
    }
}