function - onmouseover Event in For Loop JavaScript Supplies Incorrect Arguments -
this question has answer here:
so, have loop , array. in each of elements in array buttons, want have onmouseover
event.
note: code simplified make point.
for(i = 0; < array.length; i++){ var button = document.createelement("button"); button.onmouseover = function() {dosomething(i)}; }
where dosomething
accepts 1 parameter, i
.
when cursor hover on of butttons, argument supplied dosomething
- i
, length of array
, regardless of button cursor hovering over. why happen, , can ensure correct arguments supplied function?
you binding variable, not value. i.e. have created closure in functions utilize same variable i
, not new variable value of i
.
what need lock in value , 1 way can create function generator , invoke current value of i
. e.g.
for(i = 0; < array.length; i++){ var button = document.createelement("button"); button.onmouseover = function(inner_i) { return function(){dosomething(inner_i)} }(i); }
Comments
Post a Comment