# 面向对象的选项卡

一般写一个选项卡的时候,用面向过程去写是比较简单的,但是想复用的时候,就比较麻烦了,但是用面向对象的方法去写一个选项卡,写的时候虽然复杂了点,但是想复用的时候就比较简单了,只需要new一下就可以了,下面我用面向过程和面向对象的两种方法,分别来写一下选项卡的例子

# 面向过程的选项卡

我们来看一个例子,这样的结构很清晰,一目了然,但是不好复用。

<div class="tab" id="box1">
    <input type="button" value="html" class="active">
    <input type="button" value="css">
    <input type="button" value="js">
    <div style="display:block;">html</div>
    <div>css</div>
    <div>js</div>
</div>
1
2
3
4
5
6
7
8
.tab input {
    background: #f2f2f2;
    border: 1px solid #ccc;
}
.tab .active {
    background: #ccc;
}
.tab div {
    width: 300px;
    height: 250px;
    display: none;
    padding: 10px;
    background: #f2f2f2;
    border: 1px solid #ccc;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
window.onload = function () {
    var oBox = document.getElementById('box1');
    var oBtn = oBox.getElementsByTagName('input');
    var oDiv = oBox.getElementsByTagName('div');
    for(var i=0; i<oBtn.length; i++) {
        oBtn[i].index = i;
        oBtn[i].onclick = function () {
            for(var j=0; j<oBtn.length; j++) {
                oBtn[j].className='';
                oDiv[j].style.display='none';
            }
            this.className='active';
            oDiv[this.index].style.display='block';
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

例子展示
面向对象选项卡

# 面向对象的选项卡

这个例子虽然看起来逻辑复杂点,但是仔细去理解this,还是挺简单的。

function Tab(id) {
    var oBox = document.getElementById(id);
    this.oBtn = oBox.getElementsByTagName('input');
    this.oDiv = oBox.getElementsByTagName('div');

    for(var i=0; i<this.oBtn.length; i++) {
        this.oBtn[i].index = i;  // 获取索引
        var _this = this;        // 保存this
        this.oBtn[i].onclick = function() {
            _this.clickBtn(this);
            console.log(this);   // 点击哪个,指向哪个
            console.log(_this);  // Tab对象
        }
    }
}
Tab.prototype.clickBtn = function(btn) {  // 为Tab原型添加点击选项卡方法
    for(var j=0;j<this.oBtn.length; j++) {
        this.oBtn[j].className = '';
        this.oDiv[j].style.display = 'none';
    }
    btn.className = 'active';
    this.oDiv[btn.index].style.display = 'block';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

如果我们想复用,只需要加一个html,js中new一下就可以了

<div class="tab" id="box1">
    <input type="button" value="html" class="active">
    <input type="button" value="css">
    <input type="button" value="js">
    <div style="display:block;">html</div>
    <div>css</div>
    <div>js</div>
</div>
<div class="tab" id="box2">
    <input type="button" value="html" class="active">
    <input type="button" value="css">
    <input type="button" value="js">
    <div style="display:block;">html</div>
    <div>css</div>
    <div>js</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
window.onload = function() {
    var box1 = new Tab("box1");
    var box2 = new Tab("box2");
}
1
2
3
4

以上

参考链接: http://www.cnblogs.com/chiangchou/p/js-oop2.html

TOC