0

Possible Duplicate:
How do JavaScript closures work?

<script type="text/javascript"> 
function init() {    
    var pArry = document.getElementsByTagName("p");    
    for( var i=0; i<pAry.length; i++ ) {    
         pArry[i].onclick = function() {    
         alert(i);    
    } 
  }
}
</script> 
</head> 
<body onload="init();"> 
<p>test 0</p> 
<p>test 1</p> 
<p>test2</p> 
<p>test3</p> 
<p>test4</p> 

why the results are all 5? i want the reault is (0,1,2....).

Community
  • 1
  • 1
runeveryday
  • 2,751
  • 4
  • 30
  • 44

1 Answers1

1

It's referencing i, not the value of i when that function is created. Try this to freeze the value of i:

function init() {    
    var pArray = document.getElementsByTagName("p");    
    for( var i=0; i<pAry.length; i++ ) {    
        (function(i) {
            pArray[i].onclick = function() {    
                alert(i);    
            };
        })(i);
    }
}
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • 1
    This doesn't exactly freeze the value of `i` -- rather this creates a *new* `i` (via new function-scope) for each closure which has the initial value of the current `i` (from the loop) when the outer anonymous function is applied. I think not re-using `i` might make the intent more clear. –  Jun 25 '11 at 07:25