Jump to content

Help me pls


Elan

Recommended Posts

Because by the time that event handler runs, i is set to something else.  It doesn't use the value that i had when you assigned the event handler, it uses the current value of i, whatever that is.  You can use a closure to pass i as a new variable and use the value of that instead.

var i;
for (i = 0; i <= correctEls.length; i++) {
  correctEls[j].addEventListener("click", (function(idx) {
    return function() {
      whenCorrectClicked(idx);
    }
  })(i));
  i++;
}

Now that makes an anonymous function that executes immediately (IIFE), which you pass the value of i, and inside the function it uses idx for the parameter.  The IIFE returns a function which uses the value of idx, that returned function gets assigned as the click handler.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...