[thelist] JavaScript - adding onclick events to links that do not execute (advanced)
Phil Turmel
philip at turmel.org
Fri Nov 25 17:54:47 CST 2005
Tom Dell'Aringa wrote:
> 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];
> alert(foo)
> 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've never been able to wrap my head around variable scoping problems,
so I avoid them...
Javascript lets you add custom properties to any object. So I create a
custom property on each anchor, and refer to this.customproperty within
the anonymous function.
Example here:
http://www.turmel.org/TheList/AnchorOnClick.html
Have fun. (Tested with Firefox 1.0.7 and IE 6.0.2800.)
Phil
More information about the thelist
mailing list