Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Javascript: How to generate multiple functions in a for-loop?

In a html page, I need add event listeners for multiple buttons. Since the listener function for these buttons is very similar, I want to use a for-loop to finish the thing like this:

    var button_list=[button1,button2]; 
    // Let's say 'button1' and 'button2' are button elements.
    var i=0; 
    for(var button of button_list) {
      i+=1;
      button.addEventListener('click', function() {
           console.log(i); 
           // I want button1 to print '1' and button2 to print '2' 
      });
    }

I want button1 to print 1 and button2 to print 2. But above code does not work since the variable i=2 eventually, so all clicked buttons will print 2. How can I solve the problem?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda