This is driving me insane. I’m trying to use createElement inside a loop to make some <divs>, each of which has an onclick event. I threw together this test page to demonstrate it:
[CODE]
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
<style type=”text/css”>
.btn
{
width:100px;
height:50px;
background-color:#eeeeee;
border:1px solid black;
margin-bottom:10px;
}
</style>
<script language=”javascript”>
function test()
{
for(var x=0;x<5;x++)
{
yay=document.createElement(‘div’)
yay.className=”btn”
yay.id=’yay’+x
yay.innerHTML=’lorem’
yay.onclick=function(){alert(x)}
document.body.appendChild(yay)
}
}
</script>
</head>
<body onload=”test()”>
</body>
</html>
When I click on any of the boxes it alerts “5”, the final value of x after the loop ends, instead of what the value of x was when the loop executed and created the element (“0”, “1”, “2”, etc.). This is happening if FF and ie.
I also noticed in Firebug if I put a breakpoint on the “yay.onclick=function(){alert(x)}” line that it will break everytime I click on one of the boxes. Very strange…
How can I put in a variable on the yay.onclick=function(){alert(x)} line and have it “stick”? Thanks!