I have written the code in JavaScript two ways (WAY-1.html, WAY-2.html). Find the attachments. The second way (WAY-2.html) works fine as expected. Can you please do let me know why ? BTW: What is this "Closure" thing ? Also please explain a little bit !
In "Way1", because your function looped through everything when the page loaded, the value of "i" is 5, so you alert('5') every time you click.
In "Way2", you created a function call on each item. This function call passes the value that "i" was at the time of the function creation. In this way, your page is able to alert('1'), alert('2'), etc.
milani_lucie
ASKER
I am still NOT clear ... Can you please explain me in simple terms ?
WAY - 1
elements(i).onclick = function() { alert(i); };
means
if i = 0 then alert(0)
if i = 1 then alert(1)
if i = 2 then alert(2)
if i = 3 then alert(3)
if i = 4 then alert(4)
Sorry ... I cannot go through the entire story with deep URLs. Please provide me point-to-point explanation so that i can understand it better !! Even i have provided you the code also.
In "Way2", you created a function call on each item. This function call passes the value that "i" was at the time of the function creation. In this way, your page is able to alert('1'), alert('2'), etc.