面向对象 this的问题 用定时器 用了事件的之后
首先我们先布局一下 按照常规的js来做一下选项卡,
<style type="text/css"> ul, li{ list-style-type: none; margin: 0; padding: 0} #div1{ width: 300px; height: 30px; background: #ccc} #div1 li{width: 100px; float: left;; text-align: center; line-height: 30px; list-style-type: none; } .active{ background: #999} #div2{ width: 300px; height: 300px; background: #eee} #div2 div{ display: none;} </style> <script> window.onload = function(){ var oDiv1 = document.getElementById(‘div1‘); var oDiv2 = document.getElementById(‘div2‘); var oLi = oDiv1.getElementsByTagName(‘li‘); var oDiv = oDiv2.getElementsByTagName(‘div‘); for (var i = 0; i < oLi.length; i++) { oLi[i].index = i; oLi[i].onclick = function (){ for (var i = 0; i < oLi.length; i++) { oLi[i].className = ""; oDiv[i].style.display = ‘none‘; }; this.className = ‘active‘; oDiv[this.index].style.display = ‘block‘; } }; } </script> <div id="div1"> <ul> <li class="active">111111</li> <li>222222</li> <li>333333</li> </ul> </div> <div id="div2"> <div style="display:block">11111</div> <div>22222</div> <div>33333</div> </div>
下面我们来改写成面向对象
window.onload = function(){ new TabSwitch(‘div1‘,‘div2‘); new TabSwitch(‘div3‘,‘div4‘) } function TabSwitch(id1,id2){ var oDiv1 = document.getElementById(id1); var oDiv2 = document.getElementById(id2); this.oLi = oDiv1.getElementsByTagName(‘li‘); this.oDiv = oDiv2.getElementsByTagName(‘div‘); for (var i = 0; i < this.oLi.length; i++) { var _this = this; this.oLi[i].index = i; this.oLi[i].onclick = function(){ _this.tab(this); } }; } TabSwitch.prototype.tab = function(oli){ for (var i = 0; i < this.oLi.length; i++) { this.oLi[i].className = ""; this.oDiv[i].style.display = "none" } oli.className = "active"; this.oDiv[oli.index].style.display = "block" }
window.onload = function(){ new TabSwitch(‘div1‘,‘div2‘); } function TabSwitch(id1,id2){//定义构造函数 两个参数为两个大div的id。 var oDiv1 = document.getElementById(id1); var oDiv2 = document.getElementById(id2); this.oLi = oDiv1.getElementsByTagName(‘li‘);//定义为对象的属性 this.oDiv = oDiv2.getElementsByTagName(‘div‘);//定义对象属性 for (var i = 0; i < this.oLi.length; i++) { var _this = this; //改变this指向 次this指向new的对象保存在变量_this里 this.oLi[i].index = i; this.oLi[i].onclick = function(){ _this.tab(this); } }; } TabSwitch.prototype.tab = function(oli){ for (var i = 0; i < this.oLi.length; i++) { this.oLi[i].className = ""; this.oDiv[i].style.display = "none" } oli.className = "active"; this.oDiv[oli.index].style.display = "block" }
时间: 2024-10-31 02:42:42