开发者

Closure trouble: passing "event" to named function

开发者 https://www.devze.com 2023-03-19 21:02 出处:网络
I\'m debugging a bit of Javascript that was suffering from a little closure trouble - but don\'t seem to be able to pass the \"event\" argument into the function.

I'm debugging a bit of Javascript that was suffering from a little closure trouble - but don't seem to be able to pass the "event" argument into the function. Here's the problem (in shorthand):

// let's say links.length == 3
for(var i = 0; i < links.length; i++){
      links[i].onclick = function(e){
          alert(i); //closure! all links alert "3"
          // do something with "e"
      }
}

Here's my solution

//workaround

// define function outside of loop
function outer(e,i){
     return function(){
         alert(i); //closure! all links alert "3"
        // do something with "e"
    }
}

for(var i = 0; i < links.length; i++){
      links[i].onclick = outer(e,i); //uh oh! e = undefined???
}

In my workaround, I've defined a function outside the loop to prevent closure - but I am unable to pass the "e" argument to it开发者_如何学C. Can someone point me in the right direction?


Define it in the returned function.

function outer(i){
       // ------------v-- event object is passed when this function is invoked
     return function( e ){
         alert(i); 
    }
}


for(var i = 0; i < links.length; i++){
      links[i].onclick = outer(i); 
}

The event object gets passed when the event occurs, so it needs to be defined as a parameter to the function that is ultimately assigned as the handler (the function you're returning from outer()).

0

精彩评论

暂无评论...
验证码 换一张
取 消