Reputation: 190
a while back I needed to pass a variable to a function called from addEventListener
.
for(let i of ["0","1","2","3","4","5","6","7","8","9","+","-","*","/",".","(",")"]){
document.getElementById(i).addEventListener("click",()=>{add_chr(i)})
}
While this worked perfectly, I now need to have the function in the {}
instead of add_chr(i)
.
I have tried the following:
for (let i = 0; i < dict["files"].length; i++) {
//i is undefined
document.getElementById("rm" + i).addEventListener("click", (e, i) => {
console.log(i)
dict["files"].splice(i, 1)
table()
})
//function does not execute
document.getElementById("rm" + i).addEventListener("click", () => {
(i) => {
console.log(i)
dict["files"].splice(i, 1)
table()
}
})
}
This doesn't work, in the first event listener the i
is undefined and the second function never executes. (I'm always using only one addEventListener
, this is just to show my approach).
How can I pass the variable i
to the function with/ without the event
object?
Upvotes: 1
Views: 981
Reputation: 4370
Remove i
from the anonymous function as it is hiding the i
of the loop and fix the brackets of the second function.
for(let i = 0; i < 3; i++) {
// i is undefined
document.getElementById("rm" + i).addEventListener("click", (e) => {
console.log(i);
});
// function does not execute
document.getElementById("rm" + i).addEventListener("click", (e) => {
console.log(i);
});
}
<button id="rm0">rm0</button>
<button id="rm1">rm1</button>
<button id="rm2">rm2</button>
Upvotes: 3
Reputation: 1600
Out of curiosity, try changing let i = 0
to var i = 0
and also remove i
from your anonymous event handler, like this:
document.getElementById("rm" + i).addEventListener("click", (e) => { // etc.
Upvotes: 2