经常遇到的一个例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{
width: 100px;
height: 100px;
background: red;
margin: 10px 0px;
}
</style>
</head>
<body>
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</section>
<script>
// 错误做法
var div = document.getElementsByTagName("div");
console.log(div);
/* for (var i = 0; i < div.length; i++) {
div[i].onclick = function(){
console.log(i);
}
} */
// 正确做法 使用闭包存储每个i
for (var i = 0; i < div.length; i++) {
(function(i){
div[i].onclick = function(){
console.log(i+1);
}
})(i)
}
</script>
</body>
</html>