JS Loop-bound Event solution

Source: Internet
Author: User

I believe everyone has encountered a similar problem, the For loop binding event last execution is the same as the last event, such as this code

<body><ul id= "List" ><li>1</li><li>2</li><li>3</li><li>4 </li><li>5</li></ul><script>var list_obj = document.getElementsByTagName (' Li ');  for (var i = 0; I <= list_obj.length; i++) {        function() {        alert (i);}      } </script></body>

When clicked, the popup is not 0 1 2 3 4, but 5.

There are many solutions, such as creating a new function to set up a private method, and then each time new object is then bound to its method.
There is the closure of the package, the wording is relatively simple:

<body><ul id= "List" ><li>1</li><li>2</li><li>3</li><li>4 </li><li>5</li></ul><script>var list_obj = document.getElementsByTagName (' Li ');  for (var i = 0; I <= list_obj.length; i++) {      (function() {        var p =< c10> i       function() {          alert (p);        }  }) ();} </script></body>

is to add a closure to each loop and then set a temporary variable to solve the problem.

JS Loop-bound Event solution

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.