-
Notifications
You must be signed in to change notification settings - Fork 0
/
var.html
71 lines (66 loc) · 1.63 KB
/
var.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>the difference between var and let</title>
</head>
<script type="application/javascript">
/**
* 使用闭包函数作用域的方式
* @param btns
*/
function fun1(btns) {
for (var i = 0; i <= btns.length - 1; i++) {
(function (i) {
var btn = btns[i];
btn.addEventListener('click', function () {
alert(btn.innerText)
})
})(i)
}
}
/**
* 使用let块级作用域
* @param btns
*/
function fun2(btns) {
for (let i = 0; i <= btns.length - 1; i++) {
let btn = btns[i];
btn.addEventListener('click', function () {
alert(btn.innerText)
})
}
}
/**
* 使用var全局作用域方式
* @param btns
*/
function fun3(btns) {
for (var i = 0; i <= btns.length - 1; i++) {
var btn = btns[i];
btn.addEventListener('click', function () {
alert(btn.innerText)
})
}
}
// 为每一个button绑定一个点击函数,然后弹出按钮的值
window.onload = function () {
var btns = document.getElementsByTagName("button")
// 使用闭包函数解决
fun1(btns);
// let 方式
// fun2(btns);
// var
// fun3(btns)
}
</script>
<body>
<div id="box">
<button>button1</button>
<button>button2</button>
<button>button3</button>
<button>button4</button>
<button>button5</button>
</div>
</body>
</html>