为什么这段 JavaScript 代码中的 `i` 始终输出 6?
时间:2024-12-29
浏览:279
作者:佚名
各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题是《为什么这段 JavaScript 代码中的 `i` 始终输出 6?》,很明显是关于文章的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

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?
答案:
这是由于 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?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
