Home > Article > Web Front-end > js for loop output i is the same value problem
1. I recently encountered a problem during development, why is the output always 5, instead of clicking on each p, the corresponding 1, 2, 3, 4, 5 will be alerted.
The code is as follows:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>闭包演示</title> </head> <body> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <script type="text/javascript"> window.onload=function() { var ps = document.getElementsByTagName("p"); for( var i=0; i<ps.length; i++ ) { ps[i].onclick = function() { alert(i); } } } </script> </body> </html>
At this time, click on any p and the pop-up will be 5
Reason: js event processor will not run during the idle time of the thread, resulting in the final run time What is output is the last value of i, that is: 5
2. Solution: Use closure to protect the value of variable i.
//sava1:加一层闭包,i以函数参数形式传递给内层函数 for( var i=0; i<ps.length; i++ ) { (function(arg){ ps[i].onclick = function() { alert(arg); }; })(i);//调用时参数 } //save2:加一层闭包,i以局部变量形式传递给内存函数 for( var i=0; i<ps.length; i++ ) { (function () { var temp = i;//调用时局部变量 ps[i].onclick = function() { alert(temp); } })(); } //save3:加一层闭包,返回一个函数作为响应事件(注意与3的细微区别) for( var i=0; i<ps.length; i++ ) { ps[i].onclick = function(arg) { return function() {//返回一个函数 alert(arg); } }(i); } //save4:将变量 i 保存给在每个段落对象(p)上 for( var i=0; i<ps.length; i++ ) { ps[i].i = i; ps[i].onclick = function() { alert(this.i); } } //save5:将变量 i 保存在匿名函数自身 for( var i=0; i<ps.length; i++ ) { (ps[i].onclick = function() { alert(arguments.callee.i); }).i = i; } } //save6:用Function实现,实际上每产生一个函数实例就会产生一个闭包 for( var i=0; i<ps.length; i++ ) { ps[i].onclick = new Function("alert(" + i + ");");//new一次就产生一个函数实例 } //save7:用Function实现,注意与6的区别 for( var i=0; i<ps.length; i++ ) { ps[i].onclick = Function('alert('+i+')'); }
The above article briefly discusses the problem of js for loop outputting i as the same value, which is all the content shared by the editor. , I hope it can give everyone a reference, and I also hope everyone will support the PHP Chinese website.
For more articles related to the problem of js for loop outputting i as the same value, please pay attention to the PHP Chinese website!