面向对象的选项卡

本文介绍了一种使用面向对象的方法来实现网页选项卡效果的技术方案。通过创建全局变量并在window.onload中实例化对象,利用prototype扩展对象功能,实现了按钮点击切换不同内容区块的显示与隐藏。

我也不知道一个简单的选项卡,为什么要挂上面向对象那么高大上的东西。

不过无所谓了。既然有那就说一说我理解的面向对象的选项卡吧。

 

我首先把对象的创建放在了windou.onload里面,在通过创建两个全局变量进行传递获取的标签,

然后保存this,通过保存后的this把解决this指向问题,然后就是基本的选项卡内容了。其实还是很简单的,对吧。

只要你了解函数三个对象之一的prototype,并知道怎么使用的,就解决了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>面向对象的选项卡</title>
    <style>
        .box{display:none;}
    </style>
</head>
<body>
<input type="button" value="小白">
<input type="button" value="小红">
<input type="button" value="小黑">
<div class="box" style="display:block;">今年19</div>
<div class="box">今年20</div>
<div class="box">今年21</div>
<script type="text/javascript">
    window.onload = function () {
        var Main = new Person();
    };
    var oBtn = null,
        oDiv = null;
//    创建两个全局变量,让后面的prototype对象使用
    function Person(){
        this.oBtn = document.getElementsByTagName('input');
        this.oDiv = document.getElementsByClassName('box');
        //转换成全局变量
        var _this = this;
        //将这里的对象this存入_this中,方便在prototype对象中使用。
        for(var i=0;i<this.oBtn.length;i++){
            this.oBtn[i].index = i;
            this.oBtn[i].onclick = function () {
                _this.age(this);
                //这里的this指的是我们获取的input。_this值的是谁调用的Person.prototype;
            }
        }
    }
    Person.prototype.age = function (oBtn){
        // 利用prototype方法,把函数转换为对象
        for(var i=0;i<this.oBtn.length;i++){
            this.oBtn[i].className = '';
            this.oDiv[i].style.display = 'none';
        }
        oBtn.className = 'btn';
        this.oDiv[oBtn.index].style.display = 'block';
//        基本的选项卡内容
    }
</script>
</body>
</html>

最后,就是请其各路大神进行指教,并点出不足之处了。

 

转载于:https://www.cnblogs.com/Y-Love/p/7860172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值