有个网友问了个问题,以下的html,为何每次输出都是5javascript
- <html >
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>闭包演示</title>
- <style type="text/css">
- </style>
- <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>
解决方式有两种,
一、将变量 i 保存给在每一个段落对象(p)上css
- 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);
- }
- }
- }
二、将变量 i 保存在匿名函数自身 html
- 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种java
三、加一层闭包,i以函数参数形式传递给内层函数闭包
- function init3() {
- var pAry = document.getElementsByTagName("p");
- for( var i=0; i<pAry.length; i++ ) {
- (function(arg){
- pAry[i].onclick = function() {
- alert(arg);
- };
- })(i);
- }
- }
四、加一层闭包,i以局部变量形式传递给内存函数函数
- 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);
- }
- })();
- }
- }
五、加一层闭包,返回一个函数做为响应事件(注意与3的细微区别)ui
- 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);
- }
- }
又有一种方法this
六、用Function实现,实际上每产生一个函数实例就会产生一个闭包spa
- function init6() {
- var pAry = document.getElementsByTagName("p");
- for( var i=0; i<pAry.length; i++ ) {
- pAry[i].onclick = new Function("alert(" + i + ");");
- }
- }
from:http://zhouyrt.javaeye.com/blog/250073xml