Cannot read properties of undefined (reading 'styles')
时间: 2023-08-28 07:18:31 浏览: 469
vs2010中Cannot find or open the PDB file简单总结
4星 · 用户满意度95%
引用中的代码存在一个问题,for循环的条件中使用了小于等于号,导致循环多了一次,进而访问了不存在的元素,出现了"Cannot read properties of undefined (reading 'styles')"的错误。正确的代码应该是在两个for循环中都使用小于号,而不是小于等于号。引用中的代码已经修复了这个问题。
在修复后的代码中,使用了排他思想,当按钮被点击时,通过循环将所有按钮的背景颜色重置为空,然后将当前按钮的背景颜色设置为粉色。
修复后的代码如下所示:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>排他思想的运用</title>
<style>
button {
height: 100px;
width: 100px;
background-color: #fff;
}
</style>
</head>
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<script>
var btn = document.getElementsByTagName('button');
for (var i = 0; i < btn.length; i++) {
btn[i].onclick = function () {
for (var j = 0; j < btn.length; j++) {
btn[j].style.backgroundColor = '';
}
this.style.backgroundColor = 'pink';
}
}
</script>
</body>
</html>
```
修复后的代码可以正确执行,并且在点击按钮时实现了排他效果。<span class="em">1</span><span class="em">2</span>
#### 引用[.reference_title]
- *1* *2* [Uncaught TypeError: Cannot read properties of undefined (reading ‘style‘)解决办法](https://blog.csdn.net/weixin_52153452/article/details/121622117)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文