How does a function in a loop (which returns another function) work? [duplicate]
问题 This question already has an answer here: JavaScript closure inside loops – simple practical example 44 answers I\'ve been trying to assign a function to onclick event of a dynamically created \"a\" tag in JavaScript. All of the tags are created in a loop as follows: for ( var i = 0; i < 4; i++ ) { var a = document.createElement( \"a\" ); a.onclick = function( ) { alert( i ) }; document.getElementById( \"foo\" ).appendChild( a ); } The alerted value for all four links is always \"4\". Pretty