PDA

View Full Version : Problem with a for loop and storing into variables


Rok
09-06-2002, 06:41 PM
This works OK:

-----------------------------------------------------------------------
<img src="minimiraj.jpg" id="slika1">
<img src="zapri.jpg" id="slika2">
<img src="povecaj.jpg" id="slika3">
<img src="pomanjsaj.jpg" id="slika4">

for (var i = 1; i < 5; i++) {
document.getElementById('slika' + i).onclick = function() {
alert('ouch!');}}
-----------------------------------------------------------------------


But this doesn't:
-----------------------------------------------------------------------
<img src="minimiraj.jpg" id="slika1">
<img src="zapri.jpg" id="slika2">
<img src="povecaj.jpg" id="slika3">
<img src="pomanjsaj.jpg" id="slika4">

for (var i = 1; i < 5; i++) {
document.getElementById('slika' + i).onclick = function() {
alert(document.getElementById('slika' + i).src);}}
------------------------------------------------------------------------



I think it's because the for loop in this case doesn't store the function as:
alert(document.getElementById('slikai').src
but as
alert(document.getElementById('slika' + i).src
and since there is no
id="slika + i" :>
the function doesn't work.

Am I right?
And how can I solve this?

mordred
09-06-2002, 07:21 PM
You are almost correct in your error diagnose, just that it tries to concatenate a string "slika" + i the moment you click on it, and since there is no variable i defined at this moment, it doesn't work.

Anonymous functions seem to have to run in their own scope attached to the element they were assigned to and that global variables of the window namespace aren't available to them automatically (well at least in Moz1.1 which I used for thesting), but you can make use of this fact:

for (var i = 1; i < 5; i++) {
document.getElementById('slika' + i).onclick = function() {
alert(this.src);}}

Rok
09-06-2002, 07:32 PM
Great! It works.
Thanx man!

adios
09-06-2002, 09:33 PM
Actually...

The reason it doesn't work is: you're using a function literal. Function literals, like other literal values, are utilized by the system exactly as typed into your program; no run-time evaluation is carried out. This is fine in many cases; if you're assigning multiple event handlers as above, however, you'll need to use the Function constructor to evaluate the parameters each time around:

for (var i = 1; i < 5; i++) {
document.getElementById('slika' + i).onclick = new Function(
'alert(document.getElementById("slika' + i + '").src)'
);
}

Think that's it, the quotes always get me....:o

mordred
09-07-2002, 10:46 AM
Interesting, I haven't thought of using function constructors in scenarios like these, because I most often find it convenient to tie a function to the scope of the triggering element and work upon it's attributes by using the "this" statement... ok, it most surely depends on the actual scenario.


:thumbsup: