HTML
<body>
<div id='test' onClick="load()">
2
</div>
</body>
Javascript
load = function() {
test.innerHTML = "";
for (var i = 0; i < 5; i++) {
var p = document.createElement("p");
p.innerHTML = "Link";
p.onclick = function () {
alert("LINK NR: " + i)
}
document.getElementById('test').appendChild(p);
}
}
In the code above, why does the function always return the last value
?
Here is a fiddle for the code.
The p.onclick
function is only going to be called whenever there is a "click" event fired on the element and by then the value of i
would be 5 as the loop had already finished executing by that time.
What you are expecting that the function statement will be executed for each loop iteration - that is not the case. If it was indeed executed, then for each iteration you would have got an alert message, irrespective of element was clicked or not.
This can be checked by keeping a console.log
outside and inside the function and you will find for each iteration the console.log
statement outside the function will be printed in your browser's console but the console.log
statement inside function will not be executed for each iteration of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With