Home > Web Front-end > JS Tutorial > body text

Solution to the problem that the events registered in batches using for loop in javascript cannot correctly obtain the index value_javascript skills

WBOY
Release: 2016-05-16 16:25:23
Original
1179 people have browsed it

The example in this article describes the solution to the problem that JavaScript cannot correctly obtain the index value of events registered in batches using a for loop. Share it with everyone for your reference. The specific analysis is as follows:

Many friends may encounter a problem, that is, when using a for loop to register event processing functions in batches, and then finally obtaining the index value of the current element through the event processing function, it will fail. Let’s look at a code example first:

Copy code The code is as follows:






Script Home






  • Only by working hard can we have a better tomorrow.

  • Sharing and mutual assistance are the greatest source of progress.

  • Every day is new, so cherish it.

  • No one is a master at the beginning, only through hard work can growth be possible

  • Only the current time is valuable, the next second is illusory




In the above code, when the li element is clicked, the pop-up value is always four. Our original idea is that clicking the li element will display the index value of the current li element in the div. Let's briefly analyze the reasons. The reason is very simple. After the for loop is executed, the value of index has changed to four, so the above phenomenon occurs.
The code is modified as follows:

Copy code The code is as follows:






Script Home






  • Only by working hard can we have a better tomorrow.

  • Sharing and mutual assistance are the greatest source of progress.

  • Every day is new, so cherish it.

  • No one is a master at the beginning, only through hard work can growth be possible

  • Only the current time is valuable, the next second is illusory




The above code achieves our requirements. Of course, closures can also be used. The code is as follows:

Copy code The code is as follows:






Script Home






  • Only by working hard can we have a better tomorrow.

  • Sharing and mutual assistance are the greatest source of progress.

  • Every day is new, so cherish it.

  • No one is a master at the beginning, only through hard work can growth be possible

  • Only the current time is valuable, the next second is illusory




I hope this article will be helpful to everyone’s web programming based on JavaScript.

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