JavaScript using the For Loop Bulk register event does not correctly get the resolution of the index value

Source: Internet
Author: User

One problem today is that when you use the For loop to bulk register an event handler, and then finally get the index value of the current element through an event handler, it fails, looking at a code instance:

<script type= "Text/javascript" >window.onload=function() {  var olis= document.getElementsByTagName ("Li");   var oshow=document.getelementbyid ("show");    for (var index=0;index<olis.length;index++) {//olis.length=5    olis[index].onclick=  function() {      oshow.innerhtml=Index;}}  } </script>

Analysis : In the above code, when clicking on the Li element, the pop-up value is always four, and our original idea is to click on the LI element to display the current index value of the LI element in the Div, but when the For loop is finished, the value of index has changed to four, so there is a display of only 4.

Workaround :

(1) The current I is only guaranteed to exist in an array so that the exact index value can be obtained in the event.

<script type= "Text/javascript" >window.onload=function() {  var olis= document.getElementsByTagName ("Li");   var oshow=document.getelementbyid ("show");    for (var index=0;index<olis.length;index++) {    Olis[index]._index=index;    Olis[index].onclick=function() {      oshow.innerhtml=this. _index;    }  }} </script>

(2) The method of using closures

<script type= "Text/javascript" >window.onload=function() {  var olis= document.getElementsByTagName ("Li");   var oshow=document.getelementbyid ("show");    for (var index=0;index<olis.length;index++) {    (function(index) {      Olis[index].onclick=function() {        oshow.innerhtml=index;      }    }) (index)  }} </script>

JavaScript using the For Loop Bulk register event does not correctly get the resolution of the index value

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.