闭包跟作用域相关的,ECMAScript 允许使用内部函数,即函数定义和函数表达式位于另一个函数的函数体内。内部函数可以访问它们所在的外部函数中声明的所有局部变量、参数和声明的其他内部函数。当其中一个这样的内部函数在包含它们的外部函数之外被调用时,就会形成闭包。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
li{
height:30px;
background: red;
margin:10px;
}
</style>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
<script>
var lis = document.getElementsByTagName(‘li‘)
for (var i = 0; i <= lis.length; i++){
lis[i].onclick = function(num){
return function(){
alert(num);
}
}(i);
}
</script>
</html>
<script>
var lis = document.getElementsByTagName(‘li‘)
for (var i = 0; i <= lis.length; i++){
lis[i].onclick = function(){
alert(i)
}
}
</script>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
*{
margin:0;
padding:0;
}
ul{
margin:0;
list-style: none;
}
#tit li{
float:left;
width:90px;
height:40px;
}
.tit{
background: red;
}
.select{
background:gray;
}
#con div{
width:270px;
line-height:300px;
border:1px solid red;
font-size:50px;
color:red;
text-align:center;
}
.con{
display:none;
}
.show{
display:block;
}
</style>
<body>
<ul id="tit">
<li class="tit select">1</li>
<li class="tit">2</li>
<li class="tit">3</li>
</ul>
<div id="con">
<div class="con show">1</div>
<div class="con">2</div>
<div class="con">3</div>
</div>
</body>
<script>
var tits = document.getElementById(‘tit‘).getElementsByTagName(‘li‘),
cons = document.getElementById(‘con‘).getElementsByTagName(‘div‘);
for (