Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 17:03:14
Original
1099 people have browsed it

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
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template