I'm trying to create several links and bind an onclick handller to them inside a loop. On clicking the link, I want to display an alert box which indicates the link number (1 for 1st link, 2 for second link, 3 for second link and so on).
<html>
<body>
</body>
</html>
<script type = 'text/javascript'>
for (var i = 0; i < 10; i++) {
var link = document.createElement("a");
link.innerHTML = "Link " + i;
link.href = '#';
link.onclick = function () {
alert("This is the link " + i);
return false;
};
document.body.appendChild(link);
}
</script>
For some reason, I get the same alert message "This is the link 10" when I can click on any link.
Could it be because the parameters to the alert function get binded only when the function is called ? Because ultimately the value of i is 10 after the end of loop.