代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style media="screen">
button{
width: 100px;
height: 40px;
background-color: #ccc;
border: none;
outline: none;
}
div{
background-color:red;
font-size: 40px;
font-weight: bold;
width: 200px;
height: 200px;
display: none;
}
</style>
</head>
<body>
<button style="background-color:orange">1</button>
<button>2</button>
<button>3</button>
<div style="display:block">1</div>
<div>2</div>
<div>3</div>
<script type="text/javascript">
var btnBox = document.getElementsByTagName('button');
var divBox = document.getElementsByTagName('div');
for(var i = 0,len=btnBox.length;i<len;i++){
//给每一个btn添加一个index属性
btnBox[i].index = i;
btnBox[i].onclick = function(){
// console.log(this.index);
for(var j = 0;j<len;j++){
btnBox[j].style.backgroundColor = "#ccc";
divBox[j].style.display = "none";
}
this.style.backgroundColor = "orange";
divBox[this.index].style.display = "block";
}
}
</script>
</body>
</html>
第2种方法:
<script type="text/javascript">
//获取节点
var btnBox = document.getElementsByTagName('button');
var divBox = document.getElementsByTagName('div');
//绑定事件,数组的长度,数组名.length
// for(var i = 0;i<btnBox.length;i++){
//
// }
for(var i = 0,len=btnBox.length;i<len;i++){
btnBox[i].onclick = function(){
for(var j = 0;j<len;j++){
// btnBox[j].style.backgroundColor = "#ccc";
if(this==btnBox[j]){
btnBox[j].style.backgroundColor = "orange";
divBox[j].style.display = "block";
}else{
btnBox[j].style.backgroundColor = "#ccc";
divBox[j].style.display = "none";
}
}
//谁调用,指的就是谁
// console.log(this);
// console.log(i); //3
// this.style.backgroundColor = "orange";
}
}
浙公网安备 33010602011771号