JS循环绑定事件

点击li 打印对应内容的数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</body>
</html>

1
2
3
4
5
6
7
8
9
// 方法一:
var list_li = document.getElementsByTagName('li');
for (var i = 0; i < list_li.length; i++) {
(function (i) {
list_li[i].onclick = function () {
console.log(i + 1)
}
})(i)
}
1
2
3
4
5
6
7
// 方法二:
var list_li = document.getElementsByTagName('li');
for (var i = 0; i < list_li.length; i++) {
list_li[i].onclick = function () {
console.log(this.innerHTML);
}
}
1
2
3
4
5
6
7
8
// 方法三:
var list_li = document.getElementsByTagName('li');
for (var i = 0; i < list_li.length; i++) {
list_li[i].index = i;
list_li[i].onclick = function () {
console.log(this.index + 1)
}
}
1
2
3
4
5
6
7
8
9
10
方法四:
var list_li = document.getElementsByTagName('li');
for (var i = 0; i < list_li.length; i++) {
list_li[i].onclick = function (n) {
return function () {
console.log(list_li[n].innerHTML)
console.log(n + 1)
}
}(i)
}