[thelist] for loop, array and mouseover teazer

Lee Kowalkowski lee.kowalkowski at googlemail.com
Wed Sep 12 07:28:58 CDT 2007


On 12/09/2007, Chris Price <chris.price at choctaw.co.uk> wrote:
> Sorry, I don't understand what's going on.

OK, let's try again.

> I have come up with:
>
> for (i in MyDesc) {
>        var MyPointer = document.getElementById(i)
>        MyPointer.onmouseover = function () { MyWorld.nodeValue =
> MyDesc[i] + ' world' }
>        }
>    }

OK, so you're creating n functions to handle mouseover events, 1 for
each item in MyDesc.

However, all those functions have a reference to 'i', your loop
control variable.  It is the same variable for all functions, 'i' is
not inside these functions, from these functions' perspective it may
as well be a global variable, therefore, it might as well be window.i.

The value of 'i' is resolved each time the function is invoked, not
when the function is defined.

Let's suppose this loop has just completed it's second iteration (i ==
2).  There are now two onmouseover functions, both reference i, in
both functions i == 2!

--

My suggestion was trying to keep things closely aligned with the way
you were expecting it to behave.  There's more than one way of
creating a function.  Currently, you're using the function statement:

  function functionName([arg1 [, ... argN]]){body}

but you could use the Function object:

  var functionName = new Function([arg1, [... argN,]] body);

The biggest difference is that the body is all inside a string, so you
can do what you expected:

  MyPointer.onmouseover = new Function("MyWorld.nodeValue = MyDesc[" +
i + "] + ' world'");

... because 'i' will be evaluated when the function is defined and
therefore essentially be a constant value.

-- 
Lee



More information about the thelist mailing list