在JavaScript中使用var
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</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].addEventListener('click',function(){
console.log('第' + i + '个btn被点击');
});
}
// 使用闭包函数
for (var i = 0; i < btn.length; i++) {
(function (i) {
btn[i].addEventListener('click', function () {
console.log('第' + i + '个btn被点击');
});
})(i)
}
</script>
</body>
</html>
因为var没有块级作用域,点击第一个按钮会直接遍历5次输出,没有达到我们想要的点第一个按钮时显示第一个被点击
在使用闭包函数虽然可以达到效果,但是这种方法并不友好
使用let
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
for (let i = 0; i < btn.length; i++) {
(function (i) {
btn[i].addEventListener('click', function () {
console.log('第' + i + '个btn被点击');
});
})(i)
}
</script>
</body>
</html>
由于let有块级作用域,点击第一个按钮会只会遍历一次
const的使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//会直接报错,counst不能被赋值第二次
//给const赋值后,将不能修改
const name = 'hhh';
name = 'aaa';
console.log(name)
//报错,没有给name赋值
const name;
//常量的含义指对象不能修改,但是可以更改属性
const obj = {
name: 'hhh',
age: 20,
};
console.log(obj);
//修改属性
obj.name = 'aaa';
obj.age = 18;
console.log(obj);
</script>
</body>
</html>