我在 html 中有 3 个按钮(它们都有相同的类名)和一个长度为 3 的数组。当我单击第一个按钮时,我想在第一个索引中调用数据。并在我单击第二个按钮时调用第二个索引中的数据。这里是我的代码:const infoBTN = document.getElementsByClassName('infoBTN')const arr = [{name: 'Rawand'} , {name: 'Jack'} , {name: 'Max'}] ;let num = 0;const getInfo = function (){ console.log(arr[num]); }for(let i = 0 ; i<infoBTN.length ; i++){ num = i; console.log('i = ' + i + ' And num = ' + num) infoBTN[i].addEventListener('click' , getInfo)}
1 回答

天涯尽头无女友
TA贡献1831条经验 获得超9个赞
在循环内声明getInfo函数,这样它就可以对索引有一个闭包:i
const infoBTN = document.getElementsByClassName('infoBTN')
const arr = [{name: 'Rawand'} , {name: 'Jack'} , {name: 'Max'}] ;
for(let i = 0 ; i<infoBTN.length ; i++){
infoBTN[i].addEventListener('click' , () => console.log(arr[i].name));
}
<button class="infoBTN">click</button>
<button class="infoBTN">click</button>
<button class="infoBTN">click</button>
添加回答
举报
0/150
提交
取消