Hi Guys,
Im trying to create lots of divs all with there own onclick event...
Heres the code:
Seems like no matter what way i do it the onclick events all end up being the same as whichever one was created last.
I put the var otherDiv = itemDiv; line in to try and change this, but its still the same.
Can anyone help??
Cheers
Andy
Im trying to create lots of divs all with there own onclick event...
Heres the code:
Code:
<html>
<head>
<script language="javascript">
function initialise(){
data = {"item 1" : "a","item 2" : "b", "item 3" : "c"};
for (key in data)
{
itemDiv = document.createElement("DIV");
itemDiv.innerHTML = key;
itemDiv.id = key;
var otherDiv = itemDiv;
itemDiv.onclick = function(){alert(otherDiv.id);}
document.body.appendChild(itemDiv);
}
}
</script>
</head>
<body onload="initialise();">
body text.
</body>
</html>
Seems like no matter what way i do it the onclick events all end up being the same as whichever one was created last.
I put the var otherDiv = itemDiv; line in to try and change this, but its still the same.
Can anyone help??
Cheers
Andy
Comment