作用域当中的变量
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>选项卡</title>
<style type="text/css">
ul{margin: 0;padding: 0}
ul li{list-style:none;}
button.current{
background-color: red;
}
#content{
width: 260px;
height: 200px;
border: 1px solid #ddd;
overflow: hidden;
}
#content li{
display: none;
width: 250px;
height: 195px;
background-color: #ddd;
margin: 0 auto;
}
#content li.current{
display: block;
}
</style>
<script type="text/javascript">
window.onload = function(){
var btns = document.getElementsByTagName("button");
var lis = document.getElementById("content").children;
/*
//闭包
for(var i=0; i<btns.length;i++){
btns[i].onclick = function(){
// 设置当前的按钮为current
for(var j=0; j<btns.length;j++){
btns[j].removeAttribute("class");
}
this.setAttribute("class","current");
// 将内容区对应的设置为current
for(var k = 0;k<lis.length;k++){
lis[k].removeAttribute("class");
}
alert(i);
lis[i].setAttribute("class","current");
};
}*/
**使用匿名函数的调用传递外部变量到函数内部,并返回匿名函数,维护一个变量**
// 解决闭包
for(var i=0;i<btns.length;i++){
btns[i].onclick = (function(num){
return function(){
//将当前按钮设置为current
for(var j=0;j<btns.length;j++){
btns[j].removeAttribute("class");
}
this.setAttribute("class","current");
//将内容区对应的li置为current
for(var k=0;k<lis.length;k++){
lis[k].removeAttribute("class");
}
lis[num].setAttribute("class","current");
}
})(i);
}
};
</script>
</head>
<body>
<button id="h1" class="current">商品信息</button>
<button id="h2">参数配置</button>
<button id="h3">商品评价</button>
<ul id="content">
<li id="c1" class="current">商品信息的内容...</li>
<li id="c2">配置参数的内容...</li>
<li id="c3">商品评价的内容...</li>
</ul>
</body>
</html>