2019-06-12闭包做私有变量计数器 闭包做选项卡 跳转的源页面

1.闭包做私有变量计数器

闭包的用途:私有变量计数器

var count = (function(){

var a = 0;

function bb(){

a++;

return a;

}

return bb;

})();

//每调用一次count,a就自增一次

alert(count());//1

alert(count());//2

var c = count();

alert(c);//3

2.闭包做选项卡

.btns{

width: 500px;

height: 50px;

}

/*选项卡的样式*/

.btns input{

width: 100px;

height: 50px;

background-color: #ddd;/*默认灰色*/

color: #666;

border: 0px;

}

/*被选中的选项卡的样式*/

.btns input.cur{

background-color: gold;

}

/*内容区的样式*/

.contents div{

width: 500px;

height: 300px;

background-color: gold;

display: none;/*默认隐藏*/

line-height: 300px;

text-align: center;

}

/*被选中的内容区的样式*/

.contents div.active{

display: block;

}

//闭包做选项卡

window.onload = function(){

var aBtn = document.getElementById('btns').getElementsByTagName('input');

var aCon = document.getElementById('contents').getElementsByTagName('div');

// alert(aCon.length);

//循环所有的选项卡按钮

for(var i=0; i

(function(i){

//给每个选项卡按钮添加点击事件

aBtn[i].onclick = function(){

//遍历所有选项卡按钮

for(var j=0; j

//将每个选项卡按钮都设为灰色

aBtn[j].className = '';

//将每个内容区都隐藏

aCon[j].className = '';

}

//this代表当前点击的Button对象

this.className = 'cur';//当前点击的按钮为金色

// alert(i);//不加闭包时,不管点哪个按钮,i都等于3

//加闭包保存了索引值才有效

aCon[i].className = 'active';//当前点击的按钮对应的内容显示

}

})(i);

}

}

3.跳转的源页面

onclick跳转

设置window的location.href属性

onclick="window.location.href='URL'"

onclick="location='URL'"

调用window的open方法

onclick="window.open('URL','_blank');" // 在新窗口打开

onclick="window.open('URL','_self');" // 覆盖当前页

a标签跳转

Preface // 在新窗口打开

Preface // 覆盖当前页,target属性默认为_self,此处可省略

你可能感兴趣的:(2019-06-12闭包做私有变量计数器 闭包做选项卡 跳转的源页面)