问题距离
window.onload = function(){ var box = document.getElementById("box"); var num = 0; for(var i=0;i<10;i++){ box.onclick = function(){ console.log(i); //总是打印10 } } }
解决办法
window.onload = function(){ var div = document.getElementsByTagName("div"); var num = 0; for(var i=0;i<div.length;i++){ (function(i){ div[i].onclick = function(){ console.log(i); } })(i) } }
原文:http://www.cnblogs.com/dontes/p/7894874.html