Events registered in batches using the for loop cannot correctly obtain the index value, for Index

Source: Internet
Author: User

Events registered in batches using the for loop cannot correctly obtain the index value, for Index

If you use the for loop to register events in batches, the index value cannot be obtained correctly:
Many may encounter a problem, that is, when the for loop is used to register event processing functions in batches, and finally the event processing function is used to obtain the index value of the current element, it will fail, let's take a look at a code example:

1 <! DOCTYPE html> 2 

In the code above, when you click the li element, the pop-up value is always four. Our original idea is that click the li element to display the index value of the current li element in the div, the following is a brief analysis of the causes. The reason is very simple. After the for loop is executed, the index value has changed to four, so the above phenomenon occurs.
The code is modified as follows:

1 <! DOCTYPE html> 2 

The above Code meets our requirements. Of course we can also use the closure method. The Code is as follows:

1 <! DOCTYPE html> 2 

The original address is an event registered in batches using the for loop. The index value cannot be obtained correctly.


Why is the result of the for Loop correct, while foreach always shows that the index exceeds the array limit?

Foreach (int I in intNum)
{
Sum + = intNum [I];
}
The above syntax is incorrect. It should be sum + = I; here I is an element in the intNum array, that is (3, 4, 5 ). Instead of a loop child that increments from 0

Jdk 50 for loop how to obtain the index

The new features of the jdk5.0 for loop can be combined with generics to implement the simple function without manual type conversion. If you want to obtain the index of the current array or linked list, you should still use it, if it is a normal array, it is still [int]. If it is a linked list set, of course it is get (int), there is basically no other ....

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.