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