for uses the immediate function to get the value of the variable i - closure

Since i is globally scoped, the value of i is 6 when the loop ends, so the output i is 6.

var liList = ul.getElementsByTagName('li');
for (var i = 0; i < 6; i++) {
    liList[i].onclick = function () {
        alert(i) // alert 出来的总是 6,而不是 0、1、2、3、4、5
    }
};

Using an immediate function can solve this problem.

var liList = ul.getElementsByTagName('li');
for (var i = 0; i < 6; i++) {
    (function(j){
        liList[j].onclick = function () {
            alert(j) // alert出来的 0、1、2、3、4、5
        }
    })(i)
};

Guess you like

Origin blog.csdn.net/pinhmin/article/details/128953280