慕運(yùn)維8079593
2023-07-14 15:11:48
不久前,我需要將一個(gè)變量傳遞給一個(gè)名為 from 的函數(shù)addEventListener。for(let i of ["0","1","2","3","4","5","6","7","8","9","+","-","*","/",".","(",")"]){ document.getElementById(i).addEventListener("click",()=>{add_chr(i)})}雖然這工作得很好,但我現(xiàn)在需要在{}代替add_chr(i).我已經(jīng)嘗試過以下方法: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() } })}這是行不通的,在第一個(gè)事件監(jiān)聽器中,i未定義,第二個(gè)函數(shù)永遠(yuǎn)不會(huì)執(zhí)行。(我總是只使用一個(gè)addEventListener,這只是為了展示我的方法)。如何將變量傳遞i給帶有/不帶有對象的函數(shù)event?
2 回答

收到一只叮咚
TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
i從匿名函數(shù)中刪除,因?yàn)樗[藏i了循環(huán)并修復(fù)了第二個(gè)函數(shù)的括號。
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貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
出于好奇,嘗試更改let i = 0
為var i = 0
并i
從匿名事件處理程序中刪除,如下所示:
document.getElementById("rm" + i).addEventListener("click", (e) => { // etc.
添加回答
舉報(bào)
0/150
提交
取消