Possible Duplicate:
adding ‘click’ event listeners in loop
I make a demo.So let's see the HTML first.
<a href="#" id="testA">testA</a>
<a href="#" id="testB">testB</a>
<div id="showA">showA</div>
<div id="showB">showB</div>
And i want to bind click
events to Elements a
. and when it clicks, alert
the related div
. (click id="testA"
,alert id="showA"
...)
And i write the jQuery code.
var arr = ["A","B"];
for(var i=0;i<arr.length;i++){
$("#test"+arr[i]).click(function(){
alert($("#show"+arr[i]).text())
});
}
But it doesn't work. I debug this code and find that this code alert($("#show"+arr[i]).text())
only run when I click the a
element . and when I click a
. the variable i
is 3
already.
So what should I do?