...

View Full Version : Event handling with changing variable?



gorilla
04-29-2006, 08:36 PM
Hi all!
I have a small but important problem with event handling.
I tried googling but I found nothing.
This is the simplified version of the problem:



container=document.createElement("div")
for (x=1; x<=10; x++)
{
div=document.createElement("div")
div.onmouseover=function (){alert(x)}
container.appendChild(div)
}


The problem is that it will alert 10 for all the divs in the container.
What I want is that the first div alerts 1 on mouseover, the second alerts 2... the tenth alerts 10.

I already figured out that it can be solved like:



container=document.createElement("div")
for (x=1; x<=10; x++)
{
div=document.createElement("div")
div.setAttribute("onmouseover","alert("+x+")")
container.appendChild(div)
}
container.innerHTML=container.innerHTML


But this method is slower, more complicated and harder to read, and uses the primitive event-listener attaching.
I am curious how the same can be done with the first method.

I hope it was understandable.

I'd be grateful if you could help.

vwphillips
04-29-2006, 09:10 PM
container=document.createElement("div")
for (x=1; x<=10; x++)
{
div=document.createElement("div")
div.xnu=x;
div.onmouseover=function (){alert(this.xnu)}
container.appendChild(div)
}

gorilla
04-29-2006, 10:10 PM
Great! Many thanks!

Beagle
05-01-2006, 04:56 PM
Another wat to acheive this without using expando properties is:



container = document.createElement("div")

for (x=1; x<=10; ++x)
{
div = document.createElement("div")
div.onmouseover=function (){ var y = x; alert(y);}
container.appendChild(div);
}


The problem was that you were referencing x as if it were a local variable to your anonymous function, but really x was declared outside the scope of the function. By using the var keyword to create a new variable in the scope of the anonymous function, the function becomes bound up with the value of x at the time of function declaration. This is called a closure.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum