简体   繁体   English

我想调用按钮等于数组索引

[英]I wanna call button equals to array index

I have 3 buttons in html(all of them has same class Name) and an array of length 3.. soo i want to call data in first index when i clicked first button.我在 html 中有 3 个按钮(它们都有相同的类名)和一个长度为 3 的数组。所以我想在单击第一个按钮时调用第一个索引中的数据。 and call data in second index when i clicked second button.并在我单击第二个按钮时调用第二个索引中的数据。

and here my code:这里是我的代码:

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)
}

Please Help Me Please请帮帮我

Declare the getInfo function inside the loop, so it can have a closure over the i index:在循环声明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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM