点击第几个div,就打印几。
<!DOCTYPE html>
<html>
<head>
<title>闭包</title>
<style type="text/css">
.con{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 10vh;
height: 30vh;
background-color: white;
margin: auto;
}
#div1,#div2,#div3{
background-color: #f0f3f9;
width: 10vh;
height: 10vh;
margin-top: 10px;
}
#div1{
margin-top: -10px;
}
#div3{
margin-bottom: -10px;
}
</style>
</head>
<body>
<div style="position:relative;height:100vh;background-color:pink;">
<div class="con">
<div id="div1">a</div>
<div id="div2">b</div>
<div id="div3">c</div>
</div>
</div>
<script type="text/javascript">
// for(var i =1 ; i<4; i++){
// document.getElementById("div"+i).addEventListener('click',function(){alert(i)});
// }
// 无论点哪个都打印4
for(var i =1 ; i<4; i++){
(function(i){
document.getElementById("div"+i).addEventListener('click',function(){alert(i)});
})(i);
}
//点第几个打印几
// 闭包会带来 空间浪费,内存泄漏,性能消耗
</script>
</body>
</html>