前几天发表了《Javascript利用闭包(Closure)循环绑定事件》,被转载到了蓝色理想上,http://www.blueidea.com/tech/web/2008/6232.asp,引用蓝色评论中的话:
rukey67 Publish at 2008-10-14 11:55:19
这个问题很早就有很多讨论了
文章里的做法开销也比较大,不是最好的办法·
在评论中我看到新的方法和知识,现在复制过来和大家共享:
1.这是Mr.Lodar的方法:
XML/HTML代码
- <!DOCTYPE?html?PUBLIC?”-//W3C//DTD?XHTML?1.0?Transitional//EN”?”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>??? ??
- <html?xmlns=“http://www.w3.org/1999/xhtml”?>??? ??
- <head>??? ??
- ????<title>Untitled?Page</title>??? ??
- </head>??? ??
- <body>??? ??
- <ul?id=“list”>??? ??
- <li>第1条记录</li>??? ??
- <li>第2条记录</li>??? ??
- <li>第3条记录</li>??? ??
- <li>第4条记录</li>??? ??
- <li>第5条记录</li>??? ??
- <li>第6条记录</li>??? ??
- </ul>??? ??
- <script?type=“text/javascript”>??????? ??
- ????var?list_obj?=?document.getElementById(“list”).getElementsByTagName(“li”);?//获取list下面的所有li的对象数组???? ??
- ????for?(var?i?=?0;?i?<=?list_obj.length;?i++)?{???? ??
- ????????list_obj[i].onmousemove?=?function()?{???? ??
- ????????????this.style.backgroundColor?=?“#cdcdcd”;???? ??
- ????????}???? ??
- ????????list_obj[i].onmouseout?=?function()?{???? ??
- ????????????this.style.backgroundColor?=?“#FFFFFF”;???? ??
- ????????}???? ??
- ????????list_obj[i].onclick?=?new?function(n)?{ ??
- ???????????return?function(){alert(“这是第”?+(n+1)+”条记录”);} ??
- ??????? }(i); ??
- ???? ??
- ????}???? ??
- </script>??? ??
- </body>??? ??
- </html>??
2.这是freecat 的方法:
freecat Publish at 2008-10-14 17:15:35
这样更好,闭包是难,但不是你想象那样
?
JavaScript代码
- <script?type=“text/javascript”>? ??
- var?list_obj?=?document.getElementById(“list”).getElementsByTagName(“li”);?//获取list下面的所有li的对象数组? ??
- for?(var?i?=?0;?i?<=?list_obj.length;?i++)?{? ??
- (function(){? ??
- var?p?=?i ??
- list_obj[i].onmousemove?=?function()?{? ??
- this.style.backgroundColor?=?“#cdcdcd”;? ??
- }? ??
- list_obj[i].onmouseout?=?function()?{? ??
- this.style.backgroundColor?=?“#FFFFFF”;? ??
- }? ??
- list_obj[i].onclick?=?function()?{? ??
- alert(“这是第”?+?p?+?“记录”);? ??
- }? ??
- })()? ??
- }? ??
- </script>??
至于这里原理和语法我将近期整理,并更新
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂