gorilla
04-29-2006, 07: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.
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.