Loop binding events

var a = 5;

for(var i = 0;i<a ;i++){

   imglist [ i ].onclick = function(){

                console.log(i)

    }

}

When we click, we will find that what the console prints is not the index corresponding to each label, but the index corresponding to the last label all the time.

Why does this happen?
In fact, i is a global variable at this time. The click function will only look up the i value when it is executed.
First, the value of i will be looked up inside the click function, and if i is not defined, it will be looked up outside the function. The loop is completed, so no matter which label is clicked, the index of the last label will pop up.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727595&siteId=291194637