Example:
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"></Head><Body> <Button></Button> <Button></Button> <Button></Button></Body><Scripttype= "Text/javascript">window.onload=function(){ varBtns=document.getElementsByTagName ("Button"); for(varI=0; I<Btns.length;i++) {Btns[i].onclick=function() {alert (i)}; }}</Script></HTML>
The result of the execution is that each button click after the popup is 3;
Therefore, we use the characteristics of closures to solve cyclic binding, I variable assignment problem, modify the script part of the code as follows:
<script type= "Text/javascript" >window.onload=function(){ varBtns=document.getelementsbytagname ("button"); for(vari=0;i<btns.length;i++){ varCol =NewAlertfunc (i); Btns[i].onclick=Col.clickfunc; //btns[i].onclick=function () {alert (i)}; }}functionAlertfunc (i) { This. clickfunc=function() {alert (i)}; }</script>
success~
JavaScript solves loop-bound events with closures