Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem found on creating elements dynamically in a “for” loop

Status
Not open for further replies.

paradisewolf

Programmer
Mar 15, 2007
17
0
0
GB
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);

}

 
You can do it like this, and it is conceptually the simplest.
[tt]
[red]//[/red]ap.onmouseover= function(){ t.innerHTML = "icon " + i};
ap.setAttribute("x", i); //"x" any word you like
ap.onmouseover= function(){ t.innerHTML = "icon " + this.getAttribute("x")};
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top