Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
My Loop work just 2 times(Javascript Dice Game)

I want to make simple dice game when i press the images,every one of them changed just one time, that does it mean i can change the number 2 times in total. what is the problem?

let dicelenght = document.querySelectorAll('img').length;

for(let i=0; i<dicelenght;i++)
 {
     let randomNum = Math.floor(Math.random()*6) + 1;
     let randomDice = "images/dice" + randomNum + ".png";
     let Dice = document.querySelectorAll('img');
     Dice[i].addEventListener("click", function(){
         Dice[i].setAttribute('src', randomDice);
     });
 }

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are not generating the random number when the click happens. You have done that just once for every die. Instead you should only generate the random number when the user has clicked.

Also, don't query for the elements in each iteration: just do this once at the top:

let dice = document.querySelectorAll('img');

for (let die of dice) {
     die.addEventListener("click", function(){
         let randomNum = Math.floor(Math.random()*6) + 1;
         let randomDieSrc = "images/dice" + randomNum + ".png";
         die.setAttribute('src', randomDieSrc);
     });
 }
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to generate the number on click, but please also delegate

document.getElementById("diceDiv").addEventListener("click", function(e) {
  const img = e.target.closest("img")
  if (img) {
    let randomNum = Math.floor(Math.random() * 6) + 1;
    img.setAttribute('src', `images/dice${randomNum}.png`);
    img.setAttribute('alt', randomNum);
  }
});
<div id="diceDiv">
  <img id="d1" alt="d1"/><img id="d2" alt="d2"/><img id="d3" alt="d3"/><br>
  <img id="d4" alt="d4"/><img id="d5" alt="d5"/><img id="d6" alt="d6"/>
</div>

If you only want them to click once, you can test

const diceDiv = document.getElementById("diceDiv")
diceDiv.addEventListener("click", function(e) {
  const img = e.target.closest("img")
  if (img) {
    if (!img.alt.includes("d")) return; // already clicked
    let randomNum = Math.floor(Math.random() * 6) + 1;
    img.setAttribute('src', `images/dice${randomNum}.png`);
    img.setAttribute('alt', randomNum);
  }
});

document.getElementById("reset").addEventListener("click", function(e) {
  diceDiv.querySelectorAll("img").forEach(img => img.alt = img.id);
})
<div id="diceDiv">
  <img id="d1" alt="d1" /><img id="d2" alt="d2" /><img id="d3" alt="d3" /><br>
  <img id="d4" alt="d4" /><img id="d5" alt="d5" /><img id="d6" alt="d6" />
</div>
<input id="reset" type="button" value="Reset" />

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda