The accepted answer is correct, but I feel that there was no real explanation.
Let me try to explain, the problem here is in the classic missing closure.
The variable "i" is incremented by 1 for each iteration of the loop, and the on-click event is not actually executed , whether it applies only to the element a, it is summed up to the length of arrOptions, which is equal to 10.
So, the loop continues until โiโ becomes equal to 10, then, whenever the on-click event fires, it takes on the value i, which is equal to 10.
now, for the solution, in the solution we use closure, so when we apply the value 'i' to the on-click event for element a, it actually gets the exact value of i in time.
The onclick event's internal function creates a closure where it refers to the parameter (arrOptions [i]), which means that the actual i-variable is at the right time.
The function eventually closes automatically with this value, and then can return its corresponding value when the on-click event is executed.
john smith
source share