html:css
<div id="div1"> <input type="button" value="1" class="active"> <input type="button" value="2"> <input type="button" value="3"> <div style="display:block">111</div> <div>222</div> <div>333</div> </div>
css:html
#div1 div{width: 200px; height: 200px;border:1px #000 solid; display: none;} .active{background:#f00;}
js:函數
// 普通寫法this
window.onload = function () { var oParent = document.getElementById('div1'); var aInput = oParent.getElementsByTagName('input'); var aDiv = oParent.getElementsByTagName('div'); for (var i = 0; i < aInput.length; i++) { aInput[i].index = i; aInput[i].onclick = function () { for (var i = 0; i < aInput.length; i++) { aInput[i].className = ''; aDiv[i].style.display = 'none' } this.className = 'active'; aDiv[this.index].style.display = 'block' } } }
轉換過程
-先變型 儘可能不要出現函數嵌套函數,能夠有全局變量,把onload中不是賦值的語句放到單獨函數中prototype
var oParent = null; var aInput = null; var aDiv = null; window.onload = function () { oParent = document.getElementById('div1'); aInput = oParent.getElementsByTagName('input'); aDiv = oParent.getElementsByTagName('div'); init(); } function init() { for (var i = 0; i < aInput.length; i++) { aInput[i].index = i; aInput[i].onclick = change; } } function change() { for (var i = 0; i < aInput.length; i++) { aInput[i].className = ''; aDiv[i].style.display = 'none' } this.className = 'active'; aDiv[this.index].style.display = 'block' }
//改爲面向對象
全局變量就是屬性 函數就是方法 onload中建立對象 改this指向(事件或定時器問題)code
window.onload = function () { var t1 = new Tab() t1.init(); } function Tab() { this.oParent = document.getElementById('div1'); this.aInput = this.oParent.getElementsByTagName('input'); this.aDiv = this.oParent.getElementsByTagName('div'); } Tab.prototype.init = function () { var This = this; for (var i = 0; i < this.aInput.length; i++) { this.aInput[i].index = i; this.aInput[i].onclick = function (){ This.change(this); } } } Tab.prototype.change = function (obj) { for (var i = 0; i < this.aInput.length; i++) { this.aInput[i].className = ''; this.aDiv[i].style.display = 'none' } obj.className = 'active'; this.aDiv[obj.index].style.display = 'block' }
現要求再建立一個選項卡,自動輪播,只需新增div2 修改init和新增一個autoPlay方法htm
window.onload = function () { var t1 = new Tab('div1') t1.init(); var t2 = new Tab('div2') t2.init(); t2.autoPlay(); } function Tab(id) { this.oParent = document.getElementById(id); this.aInput = this.oParent.getElementsByTagName('input'); this.aDiv = this.oParent.getElementsByTagName('div'); this.iNow = 0; } Tab.prototype.autoPlay = function () { var This = this; setInterval(function () { if(This.iNow == This.aInput.length-1) { This.iNow = 0; }else { This.iNow++; } for (var i = 0; i < This.aInput.length; i++) { This.aInput[i].className = ''; This.aDiv[i].style.display = 'none' } This.aInput[This.iNow].className = 'active'; This.aDiv[This.iNow].style.display = 'block' }, 2000) }