JS for loop closure problem

Source: Internet
Author: User

For a simple example, if you want to loop through the output of each value in the array, we can use the for loop to output for example:

<script type= "Text/javascript" >var arr=["a", "B", "C", "D", "E"];for (var i=0;i<arr.length;i++) {    document.write (Arr[i]);} </script>

This is the most common one, I loop from 0 to 5 of the array of 5 values are output, where I is exactly the subscript of arr array, so loop out ~ but look at the following example will be different from what we think




As[i].onclick = function () {



}
</script>

This time will always pop-one, because the function (Onclick=function () {}) does not have this variable at all, in other words I cannot be called in this function, because there is no input value, so JS will go back to the parent to find this I variable, When I was found this for loop has actually been circulating, so I was the border town-1 so every time the pop-up is 1, to solve the problem is also simple, with the form of a closed packet can be the code as follows:

<a href= "#" >text</a> <br> <a href= "#" >link</a> <script type= "Text/javascript" > var as = document.getElementsByTagName (' a '); for (var i = as.length; i--;)     {As[i].onclick = (function () {alert (i);   return false; }) (i);} </script>

This allows you to pass I as a parameter to the inside of the function used.

JS for loop closure problem

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.