[thelist] JavaScript - adding onclick events to links that do not execute (advanced)

Tom Dell'Aringa pixelmech at yahoo.com
Fri Nov 25 13:36:36 CST 2005

--- Matt Warden <mwarden at gmail.com> wrote:

> If you alert it from within the onclick, you won't get the value.
> y has no value within that function. It only has meaningful values in
> the context of your loop. The value doesn't get evaluated at the time
> you assign the function. it gets evaluated when the function is
> *executed*. Hope that makes sense.

Right! Doh, this is a variable scope issue. Ok, I try to avoid using eval(). I can do this:

for(var y=0; y<anchors.length; y++)
		var foo = filmstripItems[y];
		anchors[y].onclick = function() {
			ajaxController('load_full', ""+foo+"");
			return false;
		anchors[y].href = "http://www.google.com/";

Now, 'foo' will alert all 3 items correctly, but within the actual anonymous function, it only
writes out the last value, seemingly because it remembers the last time through the iteration? So
they all become only one value for the second parameter...the last value. So the trick is getting
the actual value *at that time* attached to each individual onclick...


"I was in a convenience store reading a magazine and the clerk came up to me and said "This is not a library". so I said, "All right, I will talk louder then!"

More information about the thelist mailing list