面向过程与面向对象比较之tab选项卡切换

来源:互联网 发布:淘宝刷3个蓝冠多少钱 编辑:程序博客网 时间:2024/06/01 18:56
<body>    <div id="div">        <input type="button" value="选项卡1" name="">        <input type="button" value="选项卡2" name="">        <input type="button" value="选项卡3" name="">        <div>111</div>        <div>222</div>        <div>333</div>    </div></body>
<script type="text/javascript">    //面向过程的选项卡切换(用循环而不用每个元素设置id)    window.onload = function(){        var div = document.getElementById("div");        var btn = div.getElementsByTagName("input");        // alert(btn.length);        var content = div.getElementsByTagName("div");        for(var i = 0,Len = btn.length;i < Len;i++){            // alert(btn[i]);            //将每次加载DOM元素的onlcik事件时,把赋给btn的index属性            btn[i].index = i;            // console.log(i);            btn[i].onclick = function(){                for(var j = 0,Len2 = content.length;j < Len2;j++){                    content[j].style.display = "none";                }                content[this.index].style = "blcok";                //此时,i=3,因为已加载完三个onclick事件,所以当点击事件时,i=3;                // console.log(i);            };        }    };    //面向对象写法:组合使用构造函数模式和原型模式    function tabSwitch(id){        this.div = document.getElementById(id),        this.btn = div.getElementsByTagName("input"),        this.content = div.getElementsByTagName("div");        tabSwitch.prototype.tab = function(){            for(var i = 0,Len = this.btn.length;i < Len;i++){                this.btn[i].index = i;                //在事件中,this指向执行此事件的对象,因此将原来指向新对象的this赋给_this                _this = this;                this.btn[i].onclick = function(){                    for(var j = 0,Len2 = _this.content.length;j < Len2;j++){                        _this.content[j].style.display = "none";                        // console.log(_this);                    }                    _this.content[this.index].style = "block";                }            }        }        console.log(tabSwitch.prototype);//指向原型        console.log(tabSwitch.prototype.constructor);//指向构造函数    }    window.onload = function(){        var tab = new tabSwitch("div");        tab.tab();        console.log(tab.__proto__);//指向原型    }</script>

面向过程写法简单,但用起来不方便,面向对象写法效率高,用起来方便

0 0
原创粉丝点击