Here is a common problem that will face any JavaScript developer sooner or later. The code below, as simple as it looks, introduces a bug that might not be picked up by the developer during unit testing.
for(var i = 1; i<6; i++) {
var div = document.getElementById(’div’ + i);
div.onclick = doAlert(’Al’ + i);
}
The problem is that all elements that have the event attached will alert the same value. The solution is to use JavaScript Closures illustrated in the code below.
for(var i = 1; i<6; i++) {
var div = document.getElementById(’div’ + i);
div.onclick = doAlert(’Al’ + i);
}
function doAlert(what) {
return function() {
alert(what);
}
}