[Javascript] adding onclick event's with YUI

Matt McKeon matt at mysticalmonkey.com
Wed Jul 18 15:44:10 CDT 2007


Nick Fitzsimons wrote:
>> The code above works as I expect, but in a loop through the list I use a
>> counter variable in place of the hardcoded number above and every link
>> when clicked alert()'s the last number in the loop (in this case 3). But
>> if I do each of them manually it works fine.
>>
>> I've set up a test page which you can see in action and hopefully
>> understand what I'm try to say here: <http://qurl.com/ts66b>
>>
>> I'm thinking it has something to do with scope, but I can't pindown the
>> problem. Anyone have any ideas?
> 
> Hi Matt,
> 
> The important point is that it is the _variable_ to which it has access,
> not the _value_ the variable had when the closure was formed, and as the
> variable was originally inside a loop which finished executing earlier,
> the later attempt to examine it will find the value that was left in it at
> the end of the loop. (Confusing, isn't it :-)
> 

Thanks Nick and Matt.

I get the basic principle, but trying to implement it isn't working out. 
I've done another go at it here: <http://qurl.com/9c79j> but now as a 
return value for clicking a link to get the text
function getIndex(index) {
  return function() {
   alert(index);
  }
}

not the actual value that should represent.

Perhaps I'm taking this info in all the wrong way, does this new code 
look anything closer to working?

Thanks,
Matt




More information about the Javascript mailing list