<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">
//面向過程的選項卡切換(用循環(huán)而不用每個元素設置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指向執(zhí)行此事件的對象月杉,因此將原來指向新對象的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>
面向過程寫法簡單刃跛,但用起來不方便,面向對象寫法效率高苛萎,用起來方便