PDA

View Full Version : Problem found on creating elements dynamically in a “for” loop



Paradise Wolf
February 2nd, 2009, 11:34 PM
In the below code, the created link element (ap) correctly displays the right customer number in the instruction “ap.href="javascript:CallCustomer("+i+")";” but it displays the wrong icon number in the instruction “ap.onmouseover= function(){ t.innerHTML = "icon " + i};”. It always shows the last value of “i” in the for loop plus 1, no matter what link the mouse is over.

How to fix it ?



function init()
{

t = document.getElementById("test");

ctn = document.getElementById('container');

for( var i= 0; i < total_icons; i++)
{
var newdiv = document.createElement('div');
var divIdName = 'icon_pos'+i;
newdiv.setAttribute('id',divIdName);

ctn.appendChild(newdiv);

var alink = document.createElement('a');
var aIdName = 'alink'+i;
alink.setAttribute('id',aIdName);

newdiv.appendChild(alink);

var ap = document.getElementById('alink'+i);

ap.href = "javascript:CallCustomer("+i+")";

ap.onmouseover= function(){ t.innerHTML = "icon " + i};


var icon_img = document.createElement('IMG');

var imIdName = 'icon'+i;

icon_img.setAttribute('id', imIdName);

alink.appendChild(icon_img);

}

//...

}

function CallCustomer( number )
{
alert("You called Customer "+number);

}

Krilnon
February 2nd, 2009, 11:44 PM
ap.href = "javascript:CallCustomer("+i+")";
ap.onmouseover= function(){ t.innerHTML = "icon " + arguments.callee.i};
ap.onmouseover.i = i;