Possible Duplicate:
Looping through Markers with Google Maps API v3 Problem
I have a loop in which I extract some data from an array element, then add an event listener for each iteration. But I need to pass these values to each associated listener but I end up having only the last array item values in the listener. I have tried to understand from "this" but the solution seems not suitable in my case and I am confused. This is the code that I have:
for(var i=0;i<route.length;i++)
{
var input= route[i];
var sdata= input.split("@",19)
//Some code
google.maps.event.addListener(marker,'click',showiwindow);
}
function showiwindow(event)
{
var input= event.latLng;
//some code
...
document.getElementById('<%= lbl1.ClientID %>').innerHTML = sdata[1];
document.getElementById('<%= lbl2.ClientID %>').innerHTML = sdata[2];
document.getElementById('<%= lbl3.ClientID %>').innerHTML = sdata[3];
document.getElementById('<%= lbl4.ClientID %>').innerHTML = sdata[4];
......
}
When I click on a marker I only get the values of the last iteration. Coming back to the solution in that link, how do I pass the array along with the iteration value that is i. Kindly refer to the link of what I meant.
How about something like this?
for(var i=0;i<route.length;i++)
{
var input= route[i];
var sdata= input.split("@",19)
//Some code
showiwindow(sdata);
}
function showiwindow(sdata)
{
google.maps.event.addListener(marker,'click', function(event) {
var input= event.latLng;
//some code
...
document.getElementById('<%= lbl1.ClientID %>').innerHTML = sdata[1];
document.getElementById('<%= lbl2.ClientID %>').innerHTML = sdata[2];
document.getElementById('<%= lbl3.ClientID %>').innerHTML = sdata[3];
document.getElementById('<%= lbl4.ClientID %>').innerHTML = sdata[4];
......
});
}
Thanks all for the various links you have provided. Finally got a clear picture of how to deal with it:
for(var i=0;i<route.length;i++)
{
var input= route[i];
var sdata= input.split("@",19)
//Some code
google.maps.event.addListener(marker,'click',showiwindow(sdata));
}
function showiwindow(rdata)
{
return function(){
.....//some code
document.getElementById('<%= lbl4.ClientID %>').innerHTML =rdata[4];
.....
};
}
来源:https://stackoverflow.com/questions/12563277/passing-values-in-for-loop-to-event-listeners-javascript