why the results are all 5? [duplicate]
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);
}
}
精彩评论