Page 1 of 1
Apply function in loop
Posted: Tue May 20, 2008 7:46 pm
by Jonah Bron
Hello, world!
This is an issue that first showed it's ugly head in a Javascript project, and now has returned to haunt me in ActionScript. This is the scenario:
Code: Select all
var elements = document.getElementsByTagName('a');
for (var i=0;i<elements.length;i++){
elements[i].onclick = function (){
alert(this.getAttribute('href'));
}
}
What happens: Whichever link you click, it will alert the href of the
last link that was looped through. Is there a way to get around this?
This is a fictional snippet of code
Re: Apply function in loop
Posted: Wed May 21, 2008 7:16 am
by slightlymore
try using ++i instead of i++
Re: Apply function in loop
Posted: Wed May 21, 2008 8:33 am
by VladSun
slightlymore wrote:try using ++i instead of i++
???
Doesn't make any sense.
@PHPyoungster - I didn't unserstand you - this is a javascript or an actionscript problem you have?
Re: Apply function in loop
Posted: Wed May 21, 2008 4:59 pm
by Jonah Bron
That was just an example. This problem applies to actionscript and javascript alike. When you apply a function object to an object in a loop, they all end up with the same function as the last one looped through. Does that make sense?
Re: Apply function in loop
Posted: Wed May 21, 2008 6:45 pm
by VladSun
I've tried (with IE, FF) the code you posted - it works correctly. I can't reproduce the problem you describe.
Re: Apply function in loop
Posted: Wed May 21, 2008 7:17 pm
by HCBen
Try adding a break after the alert. You have to stop the loop when the element is triggered.
Re: Apply function in loop
Posted: Thu May 22, 2008 4:06 am
by VladSun
HCBen wrote:Try adding a break after the alert. You have to stop the loop when the element is triggered.
???
It's a function definition you are suggesting to place the break in...
Re: Apply function in loop
Posted: Thu May 22, 2008 2:33 pm
by pickle
slightlymore wrote:try using ++i instead of i++
Makes perfect sense.
http://ca3.php.net/manual/en/language.o ... rement.php
Re: Apply function in loop
Posted: Thu May 22, 2008 2:40 pm
by VladSun

Yes, it would decrease the time for 1 000 000 loops with 0.002sec

Re: Apply function in loop
Posted: Thu May 22, 2008 2:51 pm
by pickle
slightlymore wrote:try using ++i instead of i++
I'm guessing he thought switching the incrementer would change the value of i in the loop. It does not. However, you can see a concrete example of how changing the order of the incrementer & the variable does matter:
Code: Select all
var i = 1;
var j = 1;
alert(i++);
alert(++j);
That'll alert '1', then '2'
Re: Apply function in loop
Posted: Thu May 22, 2008 2:54 pm
by VladSun
pickle wrote:I'm guessing he thought switching the incrementer would change the value of i in the loop. It does not.
My guess also
