Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!