I'm new to JavaScript and trying to understand the behavior of this code, which attempts to assign unique onclick
handlers to different DOM elements in the array myElements[]
:
(function handleClicks(){
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = function() {
alert( 'You clicked on: ' + i );
};
})();
My understanding is that each time a DOM element is clicked, the browser should alert 'You clicked on 100' as JavaScript will use the value i
has once the function has completed
I have two questions:
If
i
only has scope within the functionhandleClicks()
how can the browser accessi
once the function has completed - surelyi
no longer exists?I tried this code by putting two HTML elements in the array
var myElements = []; myElements.push( document.getElementById('1'); myElements.push( document.getElementById('2');
http://jsfiddle.net/branmong/fS7qE/
But when the program runs, it alerts 'you clicked on: 2' for each element clicked.
Why isn't it alerting 'you clicked on: 100'. as this is surely the value of i
once the function has finished running?