遇到一个问题,为什么每次输出都是5,而不是点击每个p,就alert出对应的1,2,3,4,5。
贴上代码:
<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>
How to solve the problem that the for loop output i is the same value? -PHP Chinese website Q&A-How to solve the problem that the for loop output i is the same value? -PHP Chinese website Q&A
Let’s take a look and learn.
出现原因:js事件处理器在线程空闲时间不会运行,导致最后运行的时候输出的都是i最后的值,即:5
解决办法:使用闭包将变量i的值保护起来。