Reputation: 61
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. 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)
}
Upvotes: 0
Views: 34
Reputation: 371019
Declare the getInfo
function inside the loop, so it can have a closure over the i
index:
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>
Upvotes: 1