Javascript 即使按钮为';他已经被指派了
我有一个问题:每当我点击div时,我都想添加背景色。永远。但即使我点击更多(像一个循环),背景也会改变。如何永远设置背景色Javascript 即使按钮为';他已经被指派了,javascript,loops,click,addeventlistener,minesweeper,Javascript,Loops,Click,Addeventlistener,Minesweeper,我有一个问题:每当我点击div时,我都想添加背景色。永远。但即使我点击更多(像一个循环),背景也会改变。如何永远设置背景色 const blocks = document.querySelectorAll('.game div'); const liveNumber = document.querySelector('.lives-num'); let lives = 1; function letTheGameBegin(e, r) { const rand = Math.floo
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));
const blocks=document.querySelectorAll('.game div');
const liveNumber=document.querySelector('.livenum');
让生命=1;
让游戏开始的函数(e,r){
const rand=Math.floor(Math.random()*100);
如果(兰特<40){
e、 target.style.backgroundColor='绿色';
}否则如果(兰特<60){
e、 target.style.backgroundColor='黄色';
生活++;
}否则如果(兰特<90){
e、 target.style.backgroundColor='red';
生命--;
}否则{
e、 target.style.backgroundColor='白色';
}
liveNumber.innerHTML=生活;
如果(生命===0){
//document.querySelector('.game over').style.display='flex';
}
}
block.forEach(block=>block.addEventListener('click',让游戏开始));
我想你的意思是每个div只运行一次JS
试试这个例子,看看它是否是你所需要的:
函数让游戏开始(e,r){
const rand=Math.floor(Math.random()*100);
如果(!e.target.style.backgroundColor){
如果(兰特<40){
e、 target.style.backgroundColor='绿色';
}否则如果(兰特<60){
e、 target.style.backgroundColor='黄色';
生活++;
}否则如果(兰特<90){
e、 target.style.backgroundColor='red';
生命--;
}否则{
e、 target.style.backgroundColor='白色';
}
liveNumber.innerHTML=生活;
如果(生命===0){
//document.querySelector('.game over').style.display='flex';
}
}
}
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';
}
}
}