<!--css部分-->
<style>
*{
margin: 0;
padding: 0;
}
ul,li{
list-style: none
}
.tabbox{
width: 600px;
clear: both;
overflow: hidden;
margin: 0 auto;
border: 1px solid #ccc;
}
ul.tabnav{
width: 600px;
height: 30px;
border-bottom: 1px solid #ccc;
}
ul.tabnav li{
width: 198px;
height: 30px;
line-height: 30px;
float: left;
border-right: 1px solid #ccc;
text-align: center;
}
ul.tabnav li.active{
color: red;
}
.tabcontent{
width: 460px;
overflow: hidden;;
padding: 20px;
}
.tabcontent ul li{
float: left;
display: none;
}
.tabcontent ul li.active{
display: block;
}
</style>
<!--HTML 结构-->
<div class="tabbox">
<ul class="tabnav" id="tabnav">
<li class="item active">语文</li>
<li class="item">英语</li>
<li class="item">数学</li>
</ul>
<div class="tabcontent" id="tabcont">
<ul>
<li class="item active">语文内容</li>
<li class="item">英语内容</li>
<li class="item">数学内容</li>
</ul>
</div>
</div>
<!--javascript-->
function SwitchTab(tabbtn,tabcontent){
var tabNav = document.getElementById(tabbtn);
var tabcont = document.getElementById(tabcontent);
this.tabNavLi = tabNav.getElementsByTagName('li');
this.tabcontLi = tabcont.getElementsByTagName("li");
var _this = this; //保存创建出来的变量tabs;
for(var i=0, len=this.tabNavLi.length; i<len; i++){
this.tabNavLi[i].index = i;
this.tabNavLi[i].onclick = function (){
_this.tabshow(this); //这里的this 值得是当前点击的选项
};
}
}
SwitchTab.prototype.tabshow = function(obj){ //这里的obj 是当前被点击按钮的那个对象
for(var i=0, len=this.tabNavLi.length; i<len; i++){
this.tabNavLi[i].className = "";
this.tabcontLi[i].className = "";
}
obj.className = "active";
this.tabcontLi[obj.index].className = "active";
};
window.onload = function(){
var tabs = new SwitchTab("tabnav","tabcont");
};
</script>
//改写成面向对象最重要的是要注意this 指的是谁。 出现以下两种情况this的值应该怎么保存呢?
1. 当面向对象程序中有计时器的时候
function Aaa() {
this.a = 10;
var _this = this;
setInterval(function(){
_this.show(); //如果直接使用this,那么这里的this指向的的是window
},1000);
}
Aaa.prototype.show = function(){
alert(this.a);
};
window.onload = function() {
var aaa = new Aaa();
};
2、当面向对象程序中有事件的时候
function Bbb() {
this.a = 10;
var _this = this;
var btn = document.getElementById("btn");
btn.onclick = function() {
_this.show(); //这里的this指向的是当前对象
};
}
Bbb.prototype.show = function(){
alert(this.a);
};
window.onload = function() {
var bbb = new Bbb();
};
来源:https://www.cnblogs.com/Shinnosuke/p/5685356.html