document.getElementById("aa").innerHTML = parseInt(document.getElementById("aa").innerHTML, 10) + i
用闭包
(function (i) { img.onload = function () { .............. }})(i);
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body><button>button1</button> <br><button>button2</button> <br><button>button3</button> <br><button>button4</button> <br><hr><a>anchor1</a> <br><br><a>anchor2</a> <br><br><a>anchor3</a> <br><br><a>anchor4</a> <br><br><script> var btns = document.getElementsByTagName("button"); for ( var i = 0; i < btns.length; i++ ) { btns[i].onclick = function handler() { //alert( this.innerHTML ) console.info( i, this.innerHTML ); /* 输出 4 "button1" 4 "button2" 4 "button3" 4 "button4" */ } } alert( i ); //=> 4,JS中没有局部变量(不考虑ES6) /* 这是因为,局部变量i在函数handler调用时,依然有效; 函数handler的调用,发生在整个for循环执行完毕后,此时i=4 */ </script> <script> var anchors = document.getElementsByTagName("a"); for ( var i = 0; i < btns.length; i++ ) { ( function ( x ) { anchors[x].onclick = function() { console.info( x, this.innerHTML ); }; } ) ( i ); } /* 将变量i的值传递到立即执行的函数 (function(x){})(i), 这样,每次循环, x 的值就为当次循环的i的值,而不是直接引用变量i */</script></body></html>
采用闭包成功解决了问题,谢谢各位同仁大神的帮助