使用面向对象方式封装选项卡

前言:在学习javascript的漫长道路中,总觉得面向对象深奥难懂,学起来又枯燥乏味。
虽是如此,也不能放弃在这条道路上的探索,在一个个实例中理解原理,多看多写多练。

原则:
1.先写出普通写法,然后改成面向对象写法
2.尽量不要出现函数嵌套函数
3.可以有全局变量
4.把onload中不是赋值的语句放到单独函数中
5.this指向问题

在写这个demo的时候我直接写成了面向对象写法。

html代码

1
2
3
4
5
6
7
8
9
10
<div id="tab">
<ul class="ul1">
<li class="active">tab1</li>
<li>tab2</li>
<li>tab3</li>
</ul>
<div style="display: block;">1111111</div>
<div>222222</div>
<div>333333</div>
</div>

css样式

1
2
3
4
5
6
7
8
9
10
11
12
.ul1{height: 60px;}
.ul1 li{border:1px solid #ccc;cursor: pointer;width: 150px;height: 60px;text-align: center;line-height: 60px;list-style-type: none;float: left;}
#tab div{
width: 200px;
height: 200px;
border: 1px solid #000;
display: none;
}
.active{
background: red;
}

js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
window.onload = function(){
new tabSwitch('tab');
}
function tabSwitch(obj){
var _this = this;
var oParent = document.getElementById(obj);
this.ali = oParent.getElementsByTagName('li');
this.oDiv = oParent.getElementsByTagName('div');
for(var i=0; i<this.ali.length;i++){
this.ali[i].index = i;
this.ali[i].onclick = function(){
_this.fnClick(this);
}
}
}
tabSwitch.prototype.fnClick = function(ali){
for(var i=0; i < this.ali.length;i++){
this.ali[i].className = '';
this.oDiv[i].style.display = "none";
}
ali.className = "active";
this.oDiv[ali.index].style.display = "block";
}

演示地址:点击demo

本文参考:
http://xiaomiya.iteye.com/blog/2159445?utm_source=tuicool&utm_medium=referral
http://www.w3cfuns.com/notes/17946/cb5157357d670e083242f6642d8100ac.html