开发者

why the results are all 5? [duplicate]

开发者 https://www.devze.com 2023-03-15 13:47 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How do JavaScript closures work?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do JavaScript closures work?

<script type="text/javascript"> 
function init() {    
    var pArry = document.getElementsByTagName(开发者_如何学C"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....).


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消