javascript - Closure trouble: passing "event" to named function -
javascript - Closure trouble: passing "event" to named function -
i'm debugging bit of javascript suffering little closure problem - don't seem able pass "event" argument function. here's problem (in shorthand):
// let's links.length == 3 for(var = 0; < links.length; i++){ links[i].onclick = function(e){ alert(i); //closure! links alert "3" // "e" } }
here's solution
//workaround // define function outside of loop function outer(e,i){ homecoming function(){ alert(i); //closure! links alert "3" // "e" } } for(var = 0; < links.length; i++){ links[i].onclick = outer(e,i); //uh oh! e = undefined??? }
in workaround, i've defined function outside loop prevent closure - unable pass "e" argument it. can point me in right direction?
define in returned function.
function outer(i){ // ------------v-- event object passed when function invoked homecoming function( e ){ alert(i); } } for(var = 0; < links.length; i++){ links[i].onclick = outer(i); }
the event
object gets passed when event occurs, needs defined parameter function assigned handler (the function you're returning outer()
).
javascript closures
Comments
Post a Comment