Home > Article > Web Front-end > A brief discussion on JavaScript for loop closure
A netizen asked a question, why is the output of the following html always 5, instead of clicking on each p, the corresponding 1, 2, 3, 4, 5 will be alerted.
<html > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>闭包演示</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>产品一</p> <p>产品二</p> <p>产品三</p> <p>产品四</p> <p>产品五</p> </body> </html>
The solutions are as follows
1. Save the variable i on 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 pass i to the inner function in the form of 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);//调用时参数 } }
4. Add a layer of closure, 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;//调用时局部变量 pAry[i].onclick = function() { alert(temp); } })(); } }
5. Add A layer of closure that returns 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() {//返回一个函数 alert(arg); } }(i); } }
#6. Use Function to implement. In fact, every time a function instance is generated, a closure will be generated. Package
function init6() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = new Function("alert(" + i + ");");//new一次就产生一个函数实例 } }
7. Use Function to implement, pay attention to the difference from 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 a brief talk about JavaScript brought to you by the editor The entire content of the for loop closure is here. I hope you will pay more attention to the PHP Chinese website~
For more articles related to JavaScript for loop closure, please pay attention to the PHP Chinese website!