2017-10-13 5 views
0

私はこの問題があります: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)); 

答えて

1

divごとに1回だけ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'; 
     } 
    } 
} 
+0

それは働きました!どうもありがとうございます! –

関連する問題