Responding to a bunch of similar events, but each event has different parameters. In this case, you can use JavaScript to bind events to the for loop. Below is a good example, you can refer to the following: Sometimes we have to respond to a bunch of similar events, but the parameters of each event are different. At first, we thought it was quite simple. We couldn't use a for loop, and we found that, all use the last parameter...
Search online !!! As a result, the closure was used to solve the problem.
Code:
The Code is as follows:
For (var I = 0; I <10; I ++ ){
Btns [I]. onclick = (function (I ){
Return function () {alert (I )}
}) (I)
}
The general cause is that when you directly use btns [I]. onclick = function () {alert (I)}, the JavaScript engine will first execute the code in the for loop,
When the user starts the onclick event, JavaScript will look for I, and the result will find the I after the computation is completed, that is, 10
However, if closure is used for processing, I will become a local variable of the function.