有個網友問了個問題,以下的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