The concept of closure has never been quite understood. So is now...
A few days ago, I participated in the online examination of Alibaba's front-end. I had the following question:
The following code is available:
<p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p>var ps = document.getElementsByTagName(‘p‘);for(var i = 0; i < ps.length; i++) { ps[i].onclick = function() { alert(i); }}
Write the running result of the above Code. If you want to output 0 ~ Length-1: there are at least two ways to modify the code.
At first, I didn't know what I was taking the test. I found this problem very common only when I was reading books these two days ~~
The above code is displayed.
WhenalertWhen called,AnonymousFunction persistence for external variablesi.forThe loop has ended,iIs modified5.
That is to say, each P element is bound with a click event, that is, alert (I), but the value of I has become 5 after the end of the loop, so each click is 5.
In this case, we need to copy the current I in each loop to bring up, at a time.
Method 1 is to use the immediate execution function:
for(var i = 0; i < ps.length; i++) { (function(e) { ps[i].onclick = function() { alert(e); } })(i);}
External anonymous functions are executed immediately andiAs its parameter, the functioneThe variable hasi.
When the anonymous function that is passed to a click is executed, it haseAnd the value isNoChanged cyclically.
Method 2: return a function from an anonymous function:
for(var i = 0; i < ps.length; i++) { ps[i].onclick = (function(e) { return function() { alert(e); } })(i);}
Reference: http://bonsaiden.github.io/JavaScript-Garden/zh/#function.closures
Http://javascript.ruanyifeng.com/grammar/function.html#toc18
In fact, I am not quite familiar with it, but I wrote the following method. I don't know if it is a regular army...
Set a parent Div on the outer layer, and add a click event on the div.
<div> <p>p1</p> <p>p2</p> <p>p3</p> <p>p4</p> <p>p5</p></div>var div = document.getElementsByTagName(‘div‘)[0];var ps = document.getElementsByTagName(‘p‘);div.onclick = function(e) { for(var i = 0; i < ps.length; i++) { if(e.target == ps[i]) { alert(i); } }}
Closure in Loop