淺談JavaScript for迴圈 閉包,淺談javascript

來源:互聯網
上載者:User

淺談JavaScript for迴圈 閉包,淺談javascript

有個網友問了個問題,如下的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、加一層閉包,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+')')    }   }  

以上就是小編為大家帶來的淺談JavaScript for迴圈 閉包全部內容了,希望大家多多支援幫客之家~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.