不久前,我需要将一个变量传递给一个名为 from 的函数addEventListener。for(let i of ["0","1","2","3","4","5","6","7","8","9","+","-","*","/",".","(",")"]){ document.getElementById(i).addEventListener("click",()=>{add_chr(i)})}虽然这工作得很好,但我现在需要在{}代替add_chr(i).我已经尝试过以下方法: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() } })}这是行不通的,在第一个事件监听器中,i未定义,第二个函数永远不会执行。(我总是只使用一个addEventListener,这只是为了展示我的方法)。如何将变量传递i给带有/不带有对象的函数event?
2 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
i从匿名函数中删除,因为它隐藏i了循环并修复了第二个函数的括号。
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>
大话西游666
TA贡献1817条经验 获得超14个赞
出于好奇,尝试更改let i = 0
为var i = 0
并i
从匿名事件处理程序中删除,如下所示:
document.getElementById("rm" + i).addEventListener("click", (e) => { // etc.
添加回答
举报
0/150
提交
取消