Binding events to JavaScript in the for loop solves different event parameters _ javascript tips-js tutorial

Source: Internet
Author: User
Responding to a bunch of similar events, but each event has different parameters. In this case, you can use JavaScript to bind events to the for loop. Below is a good example, you can refer to the following: Sometimes we have to respond to a bunch of similar events, but the parameters of each event are different. At first, we thought it was quite simple. We couldn't use a for loop, and we found that, all use the last parameter...

Search online !!! As a result, the closure was used to solve the problem.

Code:

The Code is as follows:


For (var I = 0; I <10; I ++ ){
Btns [I]. onclick = (function (I ){
Return function () {alert (I )}
}) (I)
}


The general cause is that when you directly use btns [I]. onclick = function () {alert (I)}, the JavaScript engine will first execute the code in the for loop,

When the user starts the onclick event, JavaScript will look for I, and the result will find the I after the computation is completed, that is, 10

However, if closure is used for processing, 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.