用es6的方法写选项卡(和构造函数的方法很类似)

半世苍凉 提交于 2019-11-28 16:23:25

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="tab">
<div id="btns">
<button type="button">1</button>
<button type="button">2</button>
<button type="button">3</button>
</div>
<div id="boxs">
<div id="">
1
</div>
<div id="" style="display: none;">
2
</div>
<div id="" style="display: none;">
3
</div>
</div>
</div>

<script type="text/javascript">
//字面量
// 构造函数
// 类
//架构师 主程

let tab = {
btns:document.querySelectorAll('#btns button'),
boxs:document.querySelectorAll('#boxs div'),
selectedIndex:1,
init(){
//init 初始化
this.selectedBtnOfIndex(this.selectedIndex)
this.selectedBoXOfIndex(this.selectedIndex)

//给按钮增加点击事件
this.btnsEvent()

//根据下标显示对应 div


},
btnsEvent(){
//this 是 tab对象
//在对象的方法内部 使用匿名函数或者添加事件

let that = this;//1 定义that 保存this
for(let i=0;i<this.btns.length;i++){
//2 事件函数 写成箭头函数,函数中his 就跟外部this一样
this.btns[i].onclick = function(){
console.log(i,this);
//this 指的 点击的按钮
//根据下标让对应的按钮 显示 样式
// that.selectedBtnOfIndex(i) //1
this.selectedBtnOfIndex(i) //2
this.selectedBoXOfIndex(i)
}.bind(this)//3 将外部this 绑定到函数内部
}
},
selectedBtnOfIndex(index){
for(let i=0;i<this.btns.length;i++){
this.btns[i].style.color = ''
}
this.btns[index].style.color = 'red'
},
selectedBoXOfIndex(index){
for(let i=0;i<this.boxs.length;i++){
this.boxs[i].style.display = 'none'
}
this.boxs[index].style.display = 'block'
}


}
tab.init()
</script>
</body>
</html>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!