Solve closure problem with immediate execution function __ function

Source: Internet
Author: User
Tags closure
<div>div 0</div>
<div>div 1</div>

<script>
	var div = document.getElementsByTagName ("div");
	for (var i = 0; i < div.length i++) {
		div[i].addeventlistener ("click", Function () {
			alert ("div #" + i +) is CLI Cked. ")
		});
	}

</script>

When you click on Div 0 o'clock, the pop-up is shown in the following figure:


This is a classic closure problem, because of the closure, the variable i in the anonymous function in AddEventListener keeps the reference to the external variable I (that is, whether it is an anonymous function or a function outside of an anonymous function, the value of the variable i is changed, it will change), so when the loop ends, I The value is the last value, which is 2.

The solution to the problem is to add the immediate execution function so that the variable i in the anonymous function is disconnected from the reference to the variable I of the external function.



<div>div 0</div>
<div>div 1</div>

<script>
	var div = document.getElementsByTagName ("div");
	var div = document.getelementsbytagname ("div");
	for (var i = 0; i < div.length i++) {
		(function (index) {
			Div[index].addeventlistener ("click", Function () {
				alert ("div #" + index + "was clicked!")
			})
		(i);
	}

</script>


When you click on Div 0 o'clock, the value we expect will pop up.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.