I am creatind 20 dynamic div , on page load attaching onclick event to each div to alert its id but problem is on clicking any div only last div id is alerted plz help.
For example on clicking on fist div is alerting last div id.
Required result is onclick on a div should alert its own id.
Full code is given bellow.
Thanks in advance.
<html>
<head>
<script>
function __createElement(tag, cls, id, name)
{
var ele;
ele = document.createElement(tag);
if(cls!="" && cls!=undefined)
ele.className = cls;
if(id != "" && id!=undefined)
ele.id = id;
if(name!= "" && name!=undefined)
ele.name = name;
return ele;
}
function test()
{
for(var i = 0;i<20;i++)
{
var div = __createElement("div" ,"test" ,i+"test");
document.getElementById("cont").appendChild(div);
div.innerHTML = "Content"+i;
div.onclick = function ()
{
alert(i+"test");
}
}
}
setTimeout("test()",1000);
</script>
</head>
<body>
<div id=cont >
</div>
</body>
</html>
this a variable closure issue use this instead: