Let 经典案例实践
跳到导航
跳到搜索
目标:实现点击 div 变颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>let</title>
<style>
.item {
width: 80px;
height: 40px;
border: 2px solid black;
margin-left: 10px;
}
.container {
display: flex;
}
</style>
</head>
<body>
<h2>点击切换颜色</h2>
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<script>
//获取 div 元素对象
let items = document.getElementsByClassName('item');
//遍历并绑定事件
for (var i = 0; i < items.length; i++) {
items[i].onclick = function() {
//修改当前元素的背景颜色
this.style.background = 'red';
}
}
console.log(i);
console.log(window.i);
</script>
</body>
</html>
能不能用items[i].style.background = 'red';
代替this.style.background = 'red';
?答案是不行,运行会报错:Cannot read property 'style' of undefined,因为 for 循环里的变量 i 是用 var 声明的,当循环结束时 i 的值是3,var 声明的变量没有块级作用域的概念,所以 var 声明的变量 i 一直是在全局当中存在的,这一点可以通过观察console.log(i);
和console.log(window.i);
在控制台的输出进行验证。当循环结束后,i 的值就是3了,当点击某个 div 时就会执行回调函数中的代码,也就是定义的 onclick 事件处理程序,这时的 item[i] 要用到 i 的值,但是 i 的值在函数内找不到,就会向外层作用域找,找到 window.i,但此时 window.i 的值为 3,item[3] 访问不到实际 length 为 3 的元素数组中的元素,所以就 undefined 了。实际运行起来就像:
<script>
//获取 div 元素对象
let items = document.getElementsByClassName('item');
var i = 0;
items[i].onclick = function() {
//修改当前元素的背景颜色
this.style.background = 'red';
console.log('i in first function:', i);
console.log('items[i]:', items[i]);
items[i].style.background = 'red';
}
i++;
console.log('after first ++:', i);
items[i].onclick = function() {
//修改当前元素的背景颜色
this.style.background = 'red';
console.log('i in secound function:', i);
console.log('items[i]:', items[i]);
items[i].style.background = 'red';
}
i++;
console.log('after secound ++:', i);
items[i].onclick = function() {
//修改当前元素的背景颜色
this.style.background = 'red';
console.log('i in third function:', i);
console.log('items[i]:', items[i]);
items[i].style.background = 'red';
}
i++;
console.log('after third ++:', i);
</script>
after first ++: 1
after secound ++: 2
after third ++: 3
i in first function: 3
items[i]: undefined
Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at items.<computed>.onclick
i in secound function: 3
items[i]: undefined
Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at items.<computed>.onclick
i in third function: 3
items[i]: undefined
Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at items.<computed>.onclick
此时只需要用 let 来声明 for 循环里的 i