<div>
<input type="button" value="按钮1">
<input type="button" value="按钮2">
<input type="button" value="按钮3">
<input type="button" value="按钮4">
<input type="button" value="按钮5">
</div>
<script>
var btn = document.getElementsByTagName("input");
for(var i =0;i<btn.length;i++){
btn[i].onclick = function(){
for(var i =0;i<btn.length;i++){
btn[i].style.backgroundColor = "";
}
btn[i].style.backgroundColor = "red"; //出错行
// this.style.backgroundColor = "red"; // 改成this则不会报错
}
}
</script>
为什么用this可以,而用btn[i]则会报错?
报错原因:
awd.html:24 Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at HTMLInputElement.btn..onclick