<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
ul li:nth-child(1) {
background: #00ffff;
}
ul li:nth-child(2) {
background: #0011ff;
}
ul li:nth-child(3) {
background: #ff00ff;
}
ul li:nth-child(4) {
background: #aaffff;
}
ul li:nth-child(5) {
background: #ffff00;
}
ul li:nth-child(6) {
background: #00ff00;
}
</style>
</head>
<body>
<input type="button" value="a">
<input type="button" value="b">
<input type="button" value="c">
<input type="button" value="d">
<input type="button" value="e">
<input type="button" value="f">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<script>
var oInput = document.getElementsByTagName("input");
var oLi = document.getElementsByTagName("li");
for (var i = 0; i < oInput.length; i++) {
oInput[i].index = i;
oInput[i].onclick = function() {
for (var j = 0; j < oLi.length; j++) {
console.log(i); //i输出为6
oLi[j].style.display = "block";
}
console.log(i); //i输出为6
oLi[this.index].style.display = "none";
}
}
</script>
</body>
</html>
为什么这两个输出的i都为6,不应该是点击根据点击不同的input标签i是变化的吗?希望能仔细讲解,谢谢

是因为for循环在你保存的时候就应经执行完了,单机事件里面的i是输出的最后一个i,也就是6
for循环都是执行完了之后显示的,你这个应该是6个按钮对应6个li 点一个对应的li显示 js写不方便,用jquery一行就行了。
闭包问题,所有的input的onclick函数持有的都是同一个i。执行onclick方法的时候,i已经变成了6.