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

156
Visualizações
Using var in JavaScript with a for loop issue?

I know I can use the let keyword here to get the desired outcome, but I would like to know why clicking on the div items alerts #5 for each div.

var div;
var box = document.getElementById('box');
for (var i = 0; i < 5; i++) {
  div = document.createElement('div');
  div.onClick = function() {
    alert('this is box # ' + i);
  }
  box.appendChild(div);
}
<div id="box"></div>

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

0

When you assign the anonymous function to the click, it does not run its body. Its body of codes runs only when it is clicked so the first time i variable is used in the function it has already the value of 4. You need to evaluate current value of i while it is in the loop and place it in the function generated, by a function generating function. Otherwise it will take a reference to i and use its latest value always.

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