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:
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