实例 面向对象的选项卡

//28课 没懂
<!
DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>diyici</title> <style> #div1 input{background:white;} #div1 input.active{background:yellow;} #div1 div{width:200px; height:200px; background:#ccc; display:none;} </style> <script> window.onload=function (){ new TabSwitch('div1');//创建一个新的对象 } function TabSwitch(id){ var oDiv=document.getElementById(id); var _this=this; //这个this就是指刚刚创建的新对象 为了应对下面27 //变量变成属性 this.aBtn=oDiv.getElementsByTagName('input'); this.aDiv=oDiv.getElementsByTagName('div'); for(var i=0;i<this.aBtn.length;i++){ this.aBtn[i].index=i; this.aBtn[i].onclick=function (){ //不能是单单的fnClick 他现在是方法 要加上主人的 _this.fnClick(this); //如果是this.aBtn[i].onclick=this.fnClick();(而不是_this) 从右往左赋值整个方法赋给了一个事件this就变成了this.aBtn[i] } } TabSwitch.prototype.fnClick=function (oBtn){ //把函数变成对象的"方法" 方法都是通过原型来加的 //alert(this); 这个this当然是新出的对象啊P13 for(var j=0;j<this.aBtn.length;j++){ this.aBtn[j].className=""; this.aDiv[j].style.display="none"; } oBtn.className='active'; this.aDiv[oBtn.index].style.display='block'; } } </script> </head> <body> <div id="div1"> <input class="active" type="button" value="aaa"/> <input type="button" value="bbb"/> <input type="button" value="ccc"/> <div style="display:block;">aaaaaa</div> <div>dsegf</div> <div>fergef</div> </div> </body> </html>

 

之前的 贼重要的选项卡

<!DOCTYPE html>
<html>
<head>
<meta  charset="utf-8">
<title>diyici</title>
<style>
#div1 input{background:white;}
#div1 input.active{background:yellow;}
#div1 div{width:200px; height:200px; background:#ccc; display:none;}
</style>
<script>
window.onload=function (){
     var oDiv=document.getElementById('div1');
     var aBtn=oDiv.getElementsByTagName('input');
     var aDiv=oDiv.getElementsByTagName('div');
     for(var i=0;i<aBtn.length;i++){
         aBtn[i].index=i;
         aBtn[i].onclick=function (){
              for(var j=0;j<aBtn.length;j++){
                  aBtn[j].className="";
                  aDiv[j].style.display="none";
              }
              this.className='active';
              aDiv[this.index].style.display='block';
         }
     }
}
</script>
</head>
<body>
        
<div id="div1">
<input class="active" type="button" value="aaa"/>
<input type="button" value="bbb"/>
<input type="button" value="ccc"/>

 <div style="display:block;">aaaaaa</div>
 <div>dsegf</div>
 <div>fergef</div>
</div>

</body>
</html>

所以变化:

初始化变量 var oDiv=null;
全局变量要在window.onload外面

window.onload 初始化整个程序
构造函数 初始化整个对象

把变量变成对象的属性
把函数变成方法

posted @ 2019-03-03 11:36  像走了一光年  阅读(146)  评论(0编辑  收藏  举报