本文以最經典的選項卡切換為例,示範如何把一段「能跑」的面向過程代碼,平滑過渡成可複用的面向對象組件。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<style>
#div1 input {background:#CCC;}
#div1 .active {background:yellow;}
#div1 div {width:200px; height:200px; background:#CCC; display:none;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script>
window.onload=function () {
var oDiv=document.getElementById('div1');
var aBtn=oDiv.getElementsByTagName('input');
var aDiv=oDiv.getElementsByTagName('div');
var i=0;
for(i=0;i<aBtn.length;i++) {
aBtn[i].index=i;
aBtn[i].onclick=function () {
for(i=0;i<aBtn.length;i++) {
aBtn[i].className='';
aDiv[i].style.display='none';
}
this.className='active';
aDiv[this.index].style.display='block';
};
}
};
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="教育" />
<input type="button" value="財經" />
<input type="button" value="aaa" />
<div style="display:block;">1asdfasdfds</div>
<div>2xzcvxzcv</div>
<div>5332342345</div>
</div>
</body>
</html>
window.onload 裡完成初始化。onload 內部嵌套的 onclick 提到外層。onclick 一旦被拎出去,就拿不到 onload 裡的私有變量 aBtn 了,這正是需要面向對象的原因。onload(初始化整個程序)→ 構造函數(初始化一個物件) window.onload=function(){
var oTab=new TabSwitch("div1");
};
function TabSwitch(id) {
var oDiv=document.getElementById(id);
this.aBtn=oDiv.getElementsByTagName('input');
this.aDiv=oDiv.getElementsByTagName('div');
var i=0;
var _this=this; // this 指向 new 出來的物件,即 oTab
for(i=0;i<this.aBtn.length;i++) {
this.aBtn[i].index=i;
this.aBtn[i].onclick=function(){
_this.tab(this); // 以參數形式把被點擊的按鈕傳進去
};
}
};
TabSwitch.prototype.tab=function(oBtn){
for(i=0;i<this.aBtn.length;i++) {
this.aBtn[i].className='';
this.aDiv[i].style.display='none';
}
oBtn.className='active'; // 要改的是被點擊的按鈕,不是 new 出來的物件,所以這裡不用 this
this.aDiv[oBtn.index].style.display='block';
};
兩個關鍵細節值得記住:事件處理函數內部的 this 指向被觸發的 DOM 元素,因此需要事先用 _this 快取物件引用;而切換樣式時操作的對象是 oBtn,不是 this。理清這兩點,同一個類就能同時裝在頁面上多組選項卡上。
延伸閱讀:本站《JavaScript 面向對象入門教程》《JavaScript 切換特效與技巧總結》《JavaScript 錯誤與調試技巧總結》等專題。