Js closure question: is there a boss who can explain how this code is executed?

this is a common closure problem:

I would like to ask you guys, how is this code executed?
for example, when you click 3, how do you print out 2?

< hr >

1 < / div >
2 < / div >
3 < / div >
4 < / div >
5 < / div >

< script >

var elem = document.getElementsByTagName("div"); // 5div

for (var i = 0; i < 5; iPP) {
    console.log(i);
    (function (w) {
        elem[w].onclick = function () {
            console.log(w);
        };
    })(i);
}

< / script >

May.16,2021
The argument to the self-executing function in the

for loop comes from I. When you click on it, the argument I is passed to the parameter w. When you click on the third element, the div content starts at 1


your div content starts at 1, and the index for the loop starts at 0, so the pop-up value will be 1


when you click on the third element. 1-5
I starts with 0, 0-4
so when you click on div3, the third bit is 2, because 0 is the first bit of I, 1 is the second bit of I, and 2 is the third bit of I


var elem = document.getElementsByTagName('div'); // 5div

for (var i = 0; i < 5; iPP) {
    console.log(i);
    (function (w) {
        elem[w].onclick = function () {    -sharp idiv
            console.log(w);
        };
    })(i);    -sharp 0-4
}

"immediate execution function" retains the value of each "I" and binds each "div" separately,
so when you click "div3", Will output "2"
(starting at 0, so it is 2)

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3acf8-e792.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3acf8-e792.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?