JS's classic for loop closure problem solution

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="bootstrap.css">

</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<hr>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">闭包经典实例</h3>
<div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item">1</li>
<li class="list-group-item">2</li>
<li class="list-group-item">3</li>
<li class="list-group-item">4</li>
<li class="list-group-item">5</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script >
var liList=document.getElementsByTagName('li');

for(var i=0;i<liList.length;i++){

liList[i].number=i;
liList[i].onclick=function(){
alert(this.number)
}

// (function (i){
// liList[i].onclick=function( ){
// alert('Currently clicked '+ i+' number');
// }
// } )(i)
}
</script>
</body>
</html>


For a code snippet like this, beginners will take it for granted that clicking Li in turn will pop up the corresponding 0, 1, 2, 3, 4, but the actual result is that each The reason is 4 times
: every time you click to output i, there is no i inside the function, so it is searched from the external function, and the value of the external function is the value 4 after each loop, so the output of each click is 4

. Method 1: Add a layer of closure and pass i to the inner function as a function parameter:

          (function (i){ 
liList[i].onclick=function( ){
alert('Currently clicked '+ i+');
}
})(i)

Solution 2: Find an attribute to save the i value, then pop this value

        liList[i].number=i;
liList[i].onclick=function(){
alert(this.number)
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325370967&siteId=291194637