其他分享
首页 > 其他分享> > js-01_面向对象选项卡

js-01_面向对象选项卡

作者:互联网

原文链接:http://www.cnblogs.com/XChWaad/p/3329388.html

首先,面向过程的选择卡js代码台下:

                window.onload = function () {
                    var oDiv = document.getElementById("div1");
                    var oBtn = oDiv.getElementsByTagName('input');
                    var aDiv = oDiv.getElementsByTagName('div');
                    for (var i = 0; i < oBtn.length; i++) {
                        oBtn[i].index = i;
                        oBtn[i].onclick = function () {
                            for (var i = 0; i < aDiv.length; i++) {
                                oBtn[i].className = '';
                                aDiv[i].style.display = 'none';
                            }
                            this.className = "active";
                            aDiv[this.index].style.display = 'block';
                        };
                    }
                };

  基于几代码,改写为面向对象来实现,代码如下:

 window.onload = function () {
            var tab = new TabSwitch('div1');//1、把window.onload事件对应的方法写成构造函数TabSwitch
        };

        function TabSwitch(id) {
            var oDiv = document.getElementById(id);
            this.oBtn = oDiv.getElementsByTagName('input');//将外面需要访问的变量改成属性
            this.aDiv = oDiv.getElementsByTagName('div');
            var _this = this;
            for (var i = 0; i < this.oBtn.length; i++) {
                this.oBtn[i].index = i;
                this.oBtn[i].onclick = function () {
                    _this.tab(this);//这里的this变成了oBtn对象了,所以要在上面保存构造函数创建的对象代表的this
                };
            }
        };

        this.TabSwitch.prototype.tab = function (oBtn) {
            for (var i = 0; i < this.aDiv.length; i++) {
                this.oBtn[i].className = '';
                this.aDiv[i].style.display = 'none';
            }
            oBtn.className = "active";
            this.aDiv[oBtn.index].style.display = 'block';
        };

  页面的HTML如下:

    <div id="div1">
        <input class="active" type="button" name="name" value="教育" />
        <input type="button" name="name" value="财经" />
        <input type="button" name="name" value="aaa" />
        <div style="display: block;">
            lasdfae3efasdfae</div>
        <div>
            asdlkfaweiofjasdf</div>
        <div>
            sadfasdflaeifjd;slfew</div>
    </div>

  

转载于:https://www.cnblogs.com/XChWaad/p/3329388.html

标签:function,oBtn,style,01,选项卡,aDiv,js,var,oDiv
来源: https://blog.csdn.net/weixin_30872157/article/details/97515421