I'm trying to create buttons dynamically with unique listeners and handlers by using a for loop, but unfortunately I must be doing something wrong because only the last button works. Even more surprising is the fact that when clicking the last button instead of "Button No.3" it returns "Button No.4"
Bellow is the code and here is a jsfiddle http://jsfiddle.net/y69JC/4/
HTML:
<body>
<div id="ui">
some text ...
</div>
</body>
Javascript:
var uiDiv = document.getElementById('ui');
uiDiv.innerHTML = uiDiv.innerHTML + '<br>';
var results = ["Button one","Button two","Button three","Button four"];
for(var n=0;n<results.length;n++)
{
uiDiv.innerHTML = uiDiv.innerHTML + '<button id="connect'+n+'">option'+n+':'+results[n]+'</button><br>';
var tempId = document.getElementById('connect'+n);
tempId.addEventListener('click', function(){console.log("Button No."+n)}, false);
}
Thanks!