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

351
Visualizações
Input elements having the same value with 'for' loop

I have just been experimenting with JavaScript and was trying this code.

var elements = document.getElementsByTagName("p");
var n = elements.length; // Should be: 10

for (var i = 0; i < n; i++) {
  elements[i].onclick = function () {
    console.log("This is element #" + i);
  };
}
<p>Element: #1</p>
<p>Element: #2</p>
<p>Element: #3</p>
<p>Element: #4</p>
<p>Element: #5</p>

However, when the code is run, something weird occurs. Basically, for example, if you click on element #1, it will say that you've clicked on element #5.


This is what I am curious to know:

  1. Why is this occurring?
  2. Is there a fix for it?
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

change for var to let:

for (let i = 0; i < n; i++) {
  elements[i].onclick = function () {
    console.log("This is element #" + i);
  };
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the code below to correct the issues.

var elements = document.getElementsByTagName("p");
var n = elements.length;

function makeHandler(num) {
     return function() {
         console.log("This is element #" + num);
     };
};

for (var i = 0; i < n; i++) {
    elements[i].onclick = makeHandler(i + 1);
}

Let's explain the code.


Basically, in this code, makeHandler is immediately executed each time we pass through the loop, each time receiving the then-current value of i + 1 and binding it to a scoped num variable.

The outer function (makeHandler) returns the inner function (anonymous function) (which also uses this scoped num variable) and the element’s onclick is set to that inner function.

This ensures that each onclick receives and uses the proper i value (by the scoped num variable).

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