Home  >  Article  >  Web Front-end  >  JavaScript binds events in a for loop to solve the situation when event parameters are different_javascript tips

JavaScript binds events in a for loop to solve the situation when event parameters are different_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:03:141070browse

Sometimes we have to respond to a bunch of similar events, but the parameters of each event are different. At first, I thought it was quite simple, just use a for loop, but it turned out that, well, the last parameter was used. . .

Check information online! ! ! As a result, the master said to use closures to solve the

code:

Copy the code The code is as follows:

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

The probably reason is that when btns[i].onclick=function(){alert(i)} is used directly, the JavaScript engine will first convert the code in the for loop After execution,

When the user initiates the onclick event, JavaScript will look for i, and the result will be i after the operation is completed, which is 10

But if processed with a closure, i will become a function local variables of
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn