
js 闭包问题
给定以下代码:
<!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>问题:
执行此代码时,为什么输出的始终是 6?
立即学习“Java免费学习笔记(深入)”;
答案:
这是由于 javascript 中的闭包所致。当为每个输入按钮设置单击事件处理程序时,会创建一个闭包,该闭包包含当前的 i 值。单击任何按钮时,都会调用闭包,并将当前的 i 值打印到控制台。然而,由于 i 是闭包内的变量,当单击最后一个按钮时,它始终保留其最终值,即 6。
要解决此问题,可以在单击事件处理程序内使用立即调用函数表达式 (iife) 来创建新作用域,并为每个按钮指定一个唯一的 i 值:
for (var i = 0; i < oInput.length; i++) {
oInput[i].index = i;
(function(index) {
oInput[i].onclick = function() {
for (var j = 0; j < oLi.length; j++) {
console.log(index);
oLi[j].style.display = "block";
}
console.log(index);
oLi[index].style.display = "none";
}
})(i);
}以上就是为什么这段 JavaScript 代码中的 `i` 始终输出 6?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号