Tuesday, 10 September 2013

Setting the onClick property dynamically

Setting the onClick property dynamically

I am trying to set the onClick property of a dynamically generated div in
a loop but the code below is not working beyond generating the divs. Can
someone please help me out?
<script type="text/javascript">
function gengrid()
{
var i=0;
var num_stud=8;
var newdiv;
var divIdName;
var maindiv;
for(i=1;i<=num_stud;i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.onClick= function(){addit(i);};
newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
maindiv=document.getElementById('main');
maindiv.appendChild(newdiv);
}
}
gengrid();
function addit(picno)
{
alert(picno+'');
}
</script>

No comments:

Post a Comment