Sometimes it is necessary to respond to a pile of similar events, but the parameters of each event are different. At the beginning, I thought it was very simple. The loop was not available. As a result, the amount was found that the last parameter was used. Essence Essence
Check the information online! Intersection Intersection As a result, the great god said that it was solved with a closure
Code:
Copy code code as follows:
for (var I = 0; i <10; i ++) {
btns [i] .onClight = (function (i) {
Return function () {alert (i)}
}) (i)
}
The reason is that when using BTNS [i] .onClight = Function () {Alert (i)}, the JavaScript engine will first execute the code in the for loop.
When the user departs the ONCLICK incident, JavaScript will find i, and the result will find i after the operation is completed, which is 10
But if you use closure, i will become a local variable of the function