Xiaobai asks about the execution process of the closure case? Self-calling that block and the procedure when the event is triggered

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul id="box">
    <li>xx</li>
    <li>aa</li>
    <li>dd</li>
    <li>ss</li>
</ul>
<script>
    var box = document.getElementById("box");
    var liObj = box.children;
    for (var i = 0; i < liObj.length; iPP) {
        var li = liObj[i];
        (function (i) {
            li.onclick = function () {
                console.log(i)
            };
        })(i)
    }****




</script>
</body>
</html>
Jun.30,2022

what I understand is that the trigger of the for loop is completed in an instant, and the I in the subsequent order is not in accordance with 0-3. The function is immediately executed to pass the external parameters in, referencing the external I variables to form a closure, so when the li event is triggered inside, according to the principle of scope variable search, the I found is passed in.


li execute the self-calling function to bind the li tag to a click function I each time because the current scope is not available, you have to trace back to the I passing parameters to the self-calling function and output

after finding it.
Menu