With html I made 3 buttons with successive id's:
<button id="0">btn1</button>
<button id="1">btn2</button>
<button id="2">btn3</button>
I declared an array in js:
var items = ["cars", "trucks", "tankers"]
I made a loop that loops through the buttons, adding an on click listener to each of them. This onclick listener passes the iteration value i to the handle() function:
for (var i = 0; i < items.length; i++) {
document.getElementById(i).onclick = function(){handle(i)};
}
Handle function:
function handle(index){
console.log(items[index]);
}
When i run this and click the buttons, instead of getting "cars" when I click btn1, "trucks" when I click btn2 etc I get the value "undefined" instead for each button click.
I am very certain it has something to do with the handle() function not accepting i as an index. what do I do to get the result I want? Am i missing something?