<!DOCTYPE html> <html lang="zn"> <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>let</title> <script> let items = document.getElementsByClassName(".item"); //遍历并绑定事件 for (let i = 0; i < items.lenght; i++) { items[i].onclick = function () { //点击切换背景颜色 this.sytle.background = "pink"; }; } </script> <style> .container { margin: auto; } .item { display: inline-block; width: 200px; height: 100px; border: 1px solid #ccc; } </style> </head> <body> <div class="container"> <h3>点击切换背景颜色</h3> <span class="item"></span> <span class="item"></span> <span class="item"></span> </div> </body> </html>
时间: 2024-02-16 19:10:57 浏览: 213
-doctype-html-html-lang-en-dir-ltr-head-meta-name:
这段代码中存在一个拼写错误,导致代码无法正常工作。在 JavaScript 部分,`length` 被错误拼写成了 `lenght`,导致 `items` 变量没有正确地获取到所有元素,因此无法成功绑定事件。
正确的代码如下所示:
```html
<!DOCTYPE html>
<html lang="zn">
<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>let</title>
<script>
let items = document.getElementsByClassName("item"); // 修正拼写错误
//遍历并绑定事件
for (let i = 0; i < items.length; i++) {
items[i].onclick = function () {
//点击切换背景颜色
this.style.background = "pink"; // 修正拼写错误
};
}
</script>
<style>
.container {
margin: auto;
}
.item {
display: inline-block;
width: 200px;
height: 100px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="container">
<h3>点击切换背景颜色</h3>
<span class="item"></span>
<span class="item"></span>
<span class="item"></span>
</div>
</body>
</html>
```
修正拼写错误后,代码就可以正常运行了。
阅读全文