let与var最主要的区别,就是有无块级作用域。
var:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>btn1</button>
<button>btn2</button>
<button>btn3</button>
<button>btn4</button>
<script>
const btns = document.getElementsByTagName("button");
var i = 0;
for (i = 0; i < btns.length;i++){
btns[i].addEventListener("click",function () {
console.log("点击第"+(i+1)+"个button");
})
}
</script>
</body>
</html>
无论点击哪一个button都显示如下
let:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>btn1</button>
<button>btn2</button>
<button>btn3</button>
<button>btn4</button>
<script>
const btns = document.getElementsByTagName("button");
for (let i = 0; i < btns.length;i++){
btns[i].addEventListener("click",function () {
console.log("点击第"+(i+1)+"个button");
})
}
</script>
</body>
</html>
当依次点击4个button时,如下显示: