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

161
Visualizações
Javascript addeventlistener with parameter in for loop

I am trying to add onclick listeners to a list of buttons, the id of the buttons is in a range of 0-array length in this pattern btn1-btn2-btn3 and so on

I use a for loop to get the buttons by id and the event listeners against the fetched dom element:

for(var i =0; i<length; i++){
  console.log("log 1: Adding listener for "+i);
  document.getElementById("btn"+i).addEventListener("click", function(){
  myFunc(i);
  });
}

The Function

myFunc(i){
  alert(i);
}

The Problem

No matter what button I click, I always get the last number in the for loop in the alert. I have checked and all buttons have different id's and the log 1 output is correct( ten logs 0-9). However log 2 output is the last number 10 no matter what button I click.

I want to know how I can pass the iterator(i) in the onclick listener. Any advice or suggestion will be agreat help to this newbie,Thanks!

about 4 years ago · Juan Pablo Isaza
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