JavaScript for Loop closure and javascript
A netizen asked a question, the following html, why is the output every time 5, rather than clicking every p, alert generates the corresponding 1, 2, 3, 4, 5.
<Html>
There are several solutions:
1. Save variable I to each paragraph object (p)
function init() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].i = i; pAry[i].onclick = function() { alert(this.i); } } }
2. Save variable I in the anonymous function itself
function init2() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { (pAry[i].onclick = function() { alert(arguments.callee.i); }).i = i; } }
3. Add a closure, and I will pass it to the inner function as a function parameter.
Function init3 () {var pAry = document. getElementsByTagName ("p"); for (var I = 0; I <pAry. length; I ++) {(function (arg) {pAry [I]. onclick = function () {alert (arg) ;}}) (I); // parameters for calling }}
4. Add a closure, and I will pass it to the memory function as a local variable.
Function init4 () {var pAry = document. getElementsByTagName ("p"); for (var I = 0; I <pAry. length; I ++) {(function () {var temp = I; // The local variable pAry [I] During the call. onclick = function () {alert (temp );}})();}}
5. Add a closure to return a function as a response event (note the minor differences with 3)
Function init5 () {var pAry = document. getElementsByTagName ("p"); for (var I = 0; I <pAry. length; I ++) {pAry [I]. onclick = function (arg) {return function () {// returns a function alert (arg) ;}} (I );}}
6. Implement the Function. In fact, every Function instance is generated will generate a closure.
Function init6 () {var pAry = document. getElementsByTagName ("p"); for (var I = 0; I <pAry. length; I ++) {pAry [I]. onclick = new Function ("alert (" + I + ");"); // a Function instance is generated once new }}
7. Use Function implementation. Note the differences with Function 6.
function init7() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = Function('alert('+i+')') } }
The above is all the content of the JavaScript for Loop closure that xiaobian brings to you. I hope you can provide more support ~