JavaScript binds events in the for loop to resolve event arguments differently

Source: Internet
Author: User
Tags closure

Respond to a bunch of similar events, but each event has a different parameter, in which case you can use JavaScript to bind the event in the For loop, and here's a good example of how you can refer to the following

Sometimes to respond to a bunch of similar events, but the parameters of each event are different, at first thought quite simple, with a for loop do not get, the result found that, the amount is used the last parameter ...

Check the information on the Internet!!! As a result, the great God said to solve with closure

Code:

The code is as follows:

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 with Btns[i].onclick=function () {alert (i)},

When the user embarks on the onclick event, JavaScript will look for I, and the result will find I, or 10, after the operation is completed.

But with the closure, I will become a local variable of the function.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.