<!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>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
//使用点击button按钮变色,其他的不变色
// 获取元素
var btns = document.querySelectorAll('button');
// 不能直接使用 btns . onclick 因为它是一个伪数组 ,要使用的话要把它变成对象
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function() {
// console.log(i); //这里的 i 是函数里面的局部变量 ,函数里面没有值它向上找 ,循环的次数执行完的次数就是 i的值
// console.log(btns[i]); // 因为 i 的值为 5 所以btns[i]找到的值索引为 5 ,如果索引值不是5的值就是undefined(因为它有变量没有值所以是undefined)
// 先排除其他人,然后才设置自己的样式 这种排除其他人的思想我们成为排他思想
for (var i = 0; i < btns.length; i++) { // 使用for循环把所有的btn背景颜色都变成没有颜色
btns[i].style.backgroundColor = '';
}
this.style.backgroundColor = 'pink'; //然后点击是使它变色
}
}
// console.log(i); // 这里的 i 是循环执行后的长度
</script>
</body>
</html>