例子:
<style>
/* input属于行内替换元素 */
input{
width: 100px;
height: 100px;
background-color: red;
color: white;
}
</style>
<input type="button" name="buttons" value="第一个">
<input type="button" name="buttons" value="第二个">
<input type="button" name="buttons" value="第三个">
<input type="button" name="buttons" value="第四个">
<input type="button" name="buttons" value="第五个">
<input type="button" name="buttons" value="第六个">
<script>
//获取到所有input标签的一个数组
var radios = document.getElementsByName("buttons");
//通过循环为每个标签注册点击事件
for (var i = 0; i < radios.length; i++) {
radios.item(i).onclick = function () {
//在点击某个按钮之前,需要把所得按钮的背景颜色重置
for (var j = 0; j < radios.length; j++) {
radios[j].style.backgroundColor = "red"
}
//设置点击的按钮时,背景颜色变化
radios[i].style.backgroundColor = "green"
}
}
</script>
解释:在这个案例中,我们打算实现鼠标点击那个按钮,那么那个按钮的颜色变成绿色,其他的按钮全部是红色,但是当我们随机点击一个按钮,没有出现效果,反而报错。
报错:Uncaught TypeError: Cannot read property 'style' of undefined at HTMLInputElement.radios.item.onclick (01.html:41)
原因:for循环是在页面加载的时候就执行完毕了,也就是说当页面加载完毕以后,已经为六个按钮注册了点击事件 ,经过循环以后此时的i 值已经变为了7( radios[i].style.backgroundColor = "green" ),但是标签元素数组的长度为6,并不存在第7个标签元素。
解决方法:把这行代码:radios[i].style.backgroundColor = "green" 替换成为 this.style.backgroundColor = "green" 因为this表示当前点击事件绑定的标签元素,指向着的每次点击的按钮
成功: