I need to pass a value to a function that is executed by an event. This value will be the iteration number that you have in a loop. Or what is the same, I want to pass a number to a function that identifies the HTML element that I have clicked on.
I put the code:
pasos = this.miElemento.getElementsByTagName('li');
var i;
for (i = 0; i < pasos.length; i++) {
pasos[i].addEventListener('click', (e) => { miFuncion(i); });
}
If I click the element with the 'li' tag, the function will be called miFuncion
but the value of i that I will receive will be equal to pasos.length
and not the value of the number i that I have as I assign the event to the element.
You have several options, perhaps the easiest would be to use
let
instead ofvar
to define the variable that is used to iterate through the loop.By using
var
you are defining the variablei
as global (or limited to the function) and its value at the end of the loop will be the same no matter what youli
click on. Instead,let
it is block-scoped, that is, its scope is the block in which it is defined, so its value will be "frozen" at what it had in that iteration of the loop, instead of whatever value it has at the end. loop.Here you can see it working (note how the definition of
i
moves directly inside the loop and not outside):Other options could be: add a data-attribute with the order inside the loop, or compare the elements of the list with the clicked one to compare it. But what is proposed above is going to be cleaner and simpler.