Closures in for loops

Now to implement a small function

<ul>

<li>0</li>

<li>1</li>

<li>2</li>

<li>3</li>

</ul>

Click 0123 to output ordered numbers!

If you guess correctly, you will write this confidently,

<script type="text/javascript">

var li = document.getElementsByTagName ('li');

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

li[i].addEventListener('click',function () {

console.log(i);
	
},false)

}

</script>

Then you will find that all output 4, which turns out to be wrong!

analyze:  

for loop events in the loop

function () {
	
	console.log(i);
	
	}

But that anonymous function is called after the for loop is finished (when the user clicks the link),

When calling, you need to find the variable i , there is no i inside the function, so use the external variable i ,

When looping, when i is not less than li.length, the value of i is 4, so this 4 will be output when clicked.

The correct way is

<script type="text/javascript">
	
var li = document.getElementsByTagName ('li');
	
for (var i = 0; i < li.length; i ++) {
	
(function (i) {
	
li[i].addEventListener('click',function () {
		
console.log(i);
		
},false)
		
}(i))
	
}
	
</script>

Add an immediate execution function to the periphery and use i to pass parameters

simulate its loop

first lap
(function (0) {

	li[0].addEventListener('click',function () {
	
	console.log(0);
	
	},false)
	
	}(0))

}

second lap
(function (1) {

	li[1].addEventListener('click',function () {
	
	console.log(1);
	
	},false)
	
	}(1))

}

......

Equivalent to binding events to each element

Guess you like

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