So, I have a for loop and an array. in each of the elements in that array are buttons, which I want to all have an onmouseover
event.
Note: code is simplified to make my point.
for(i = 0; i < array.length; i++){
var button = document.createElement("button");
button.onmouseover = function() {doSomething(i)};
}
where doSomething
accepts one parameter, i
.
When the cursor does hover over any of the butttons, the argument supplied to doSomething
- i
, is always the length of array
, regardless of which button the cursor is hovering over. Why does this happen, and what can I do to ensure the correct arguments are supplied to the function?