Question : Why does this code seem to be retrospectively changing the onclick function values?

Hi there,

I have the below code, which is meant to dynamically add links to the div 'main', in addition to adding the links it is meant to assign an onclick function to each of the new links using the value of the global variable 'count' as a parameter.

The new links are added correctly but the onclick value for each function seems to be the latest 'count' value as opposed to incremental count values.

The intention was that by using getElementById("link"+count), I could set the onclick function assigning the current count as the parameter. This doesn't seem to be working. I've been playing around with the code for a while but don't understand what I'm doing wrong, or why the code is behaving the way it is.

Any help would be greatly appreciated, thanks in advance.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
var count=0;
 
function add_link(){
	var main_div=document.getElementById("main");
	
	var link_div=document.createElement("div");
	link_div.innerHTML='link '+count+'';
 
	main_div.appendChild(link_div);
 
	var new_link=document.getElementById("link"+count);
	new_link.onclick= function(){ alert(count); };
 
	count++;
}
Open in New Window Select All

Answer : Why does this code seem to be retrospectively changing the onclick function values?

Hi,

Is this line just for testing to see that the right id was assigned?
new_link.onclick= function(){ alert(count); };

if so try changing it to this..
new_link.onclick= function(){ alert(this.id); };

Because the onclick function is always going to tell you the final value of count after its been incremented.

A great tool for mozilla firefox is firebug, which lets you inspect the id's of elements that have been created dynamically.
Random Solutions  
 
programming4us programming4us