A netizen asked a question, as shown in the following html, why does each output be 5, instead of clicking on each p, you will alert the corresponding 1, 2, 3, 4, 5.
<html > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Closing Demo</title> <script type="text/javascript"> function init() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = function() { alert(i); } } } </script> </head> <body onload="init();"> <p>Product 1</p> <p>Product 2</p> <p>Product 3</p> <p>Product 4</p> <p>Product 5</p> </body> </html>There are several solutions
1. Save the 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 the 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 layer of closure, and i is passed to the inner function in the form of function parameters.
function init3() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { (function(arg){ pAry[i].onclick = function() { alert(arg); }; })(i);//Arguments when calling} } }4. Add a layer of closure, and i is passed to the memory function in the form of a local variable
function init4() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { (function () { var temp = i;// Local variable pAry[i].onclick = function() { alert(temp); } })(); } }5. Add a layer of closure and return a function as a response event (note the subtle difference from 3)
function init5() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = function(arg) { return function() {//Return a function alert(arg); } }(i); } }6. Implemented with Function, in fact, every time a function instance is generated, a closure will be generated.
function init6() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = new Function("alert(" + i + ");");//new generates one function instance at a time} }7. Use Function to implement it, pay attention to the difference between 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 the brief discussion on the JavaScript for loop closure that the editor brings to you. I hope everyone will support Wulin.com more~