JavaScript binds events in a for loop to resolve cases where the event parameters are different

  • 2020-03-30 01:27:17
  • OfStack

Sometimes it is necessary to respond to a bunch of similar events, but each event has different parameters. At first, I thought it was easy to use a "for" loop.

Search information on the Internet!! It turns out that the solution is closures

Code:
 
for(var i=0;i<10;i++){ 
btns[i].onclick=(function(i){ 
return function(){alert(i)} 
})(i) 
} 

Presumably because the JavaScript engine executes the code in the for loop first when BTNS [I].onclick=function(){alert(I)} is used directly,

When the user embarks on the onclick event, the JavaScript looks for I, and the result is that when the operation is complete, it finds I, which is 10

But with closures, I becomes a local variable of the function

Related articles: