点击li 打印对应内容的数字
<!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>
// 方法一:
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)
}
// 方法二:
var list_li = document.getElementsByTagName('li');
for (var i = 0; i < list_li.length; i++) {
list_li[i].onclick = function () {
console.log(this.innerHTML);
}
}
// 方法三:
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)
}
}
方法四:
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)
}
网友评论