1,在正常的js中
for(var i=0; i< 6; i++){
console.log(i);
}
输出的结果为:0,1,2,3,4,5
2,当运用到代码中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>闭包</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul,li{
list-style: none;
}
.list{
width: 100%;
height: 300px;
background: #f99;
}
.list li{
width: 100%;
height: 40px;
background: yellow;
margin-bottom: 10px;
}
.center{
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<ul class="list">
<li class="center">1</li>
<li class="center">2</li>
<li class="center">3</li>
<li class="center">4</li>
<li class="center">5</li>
<li class="center">6</li>
</ul>
<script type="text/javascript">
var list = document.getElementsByTagName("li");
//console.log(list.length); //6 这里每次打印结果都是6
for(var i = 0;i < list.length; i++){
list[i].onclick = function(){
console.log(i);
}
}
</script>
</body>
</html>
上述问题就出在作用域块中,下面说一下三种解决方法
第一种 通过index属性
for(var i = 0;i < list.length; i++){
list[i].index = i;
list[i].onclick = function(){
var index = this.index;
console.log(index);
}
}
第二种 闭包
for( var i = 0; i < list.length; i++){
(function(index){
list[i].onclick = function(){
console.log(i);
}
})(i)
}
第三种 let
for(let i = 0; i < 6; i++){
setTimeout(function(){
console.log(i);
},1000)
}