for循环记数器
来源:互联网 发布:付费炒股软件排名 编辑:程序博客网 时间:2024/05/21 21:47
如下的html,为什么每次输出都是5,而不是点击每个p,就alert出对应的1,2,3,4,5。
<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> 解决方式有两种,1、将变量 i 保存给在每个段落对象(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、将变量 i 保存在匿名函数自身 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种3、加一层闭包,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);//调用时参数 } } 4、加一层闭包,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); } })(); } } 5、加一层闭包,返回一个函数作为响应事件(注意与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、用Function实现,实际上每产生一个函数实例就会产生一个闭包 function init6() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = new Function("alert(" + i + ");");//new一次就产生一个函数实例 } } 再增加一种7、用Function实现,注意与6的区别function init7() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = Function('alert('+i+')') }
1 0
- for循环记数器
- 页面记数器
- for循环
- For循环
- for循环
- for 循环
- for循环
- for循环
- for循环
- for循环
- for 循环.
- for 循环
- for循环
- For循环
- for循环
- FOR循环
- for循环
- for循环
- 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? (基础c++)
- 中英文对照 —— 英语语法与文法概念
- ExpressBox 2400
- 使用listView事件实现上拉加载
- perl 根据div 标签 查找id属性的值
- for循环记数器
- C# Dictionary 字典简介
- 发布开源框架到CocoaPods
- 欢迎使用CSDN-markdown编辑器
- Sql Server 2014/2012/2008/2005 数据库还原出现 3154错误的解决办法
- JAVA反射机制
- Win7下完全卸载Oracle 11g的步骤
- Freeswitch内核研究之录音
- mysql获取数据库名 表名及列名