Reputation: 9570
I have an array of 7 marker points , I want to add a click handler to each marker. I am trying to do so like this
for (var i = 0; i <= 7; i++) {
google.maps.event.addListener(googleMarkerPoints[i], 'click', function () {
var selector = "div[data-num='" + i + "']";
$(selector).css({ "background-color": "#999" });
});
}
googleMarkerPoints
is filled like this:
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var latitude = obj.Latitude;
var longitude = obj.Longitude;
var title = obj.Title;
var thisLatlng = new google.maps.LatLng(latitude, longitude);
var thismarker = new google.maps.Marker({
position: thisLatlng,
map: map,
title: title
});
googleMarkerPoints.push(thismarker);
}
my problem is that every time that I click any marker in the handler selector
gets filled with
"div[data-num='7']"
I was hoping that data-num would be different for each marker going 1 through 7, why are these click handlers not working properly??
Upvotes: 0
Views: 72
Reputation: 82277
You are closing over i
and so you only get one value for all of the events. Try passing the i
value into your anonymous function like this:
for (var i = 0; i <= 7; i++) {
(function(i){
google.maps.event.addListener(googleMarkerPoints[i], 'click', function () {
var selector = "div[data-num='" + i + "']";
$(selector).css({ "background-color": "#999" });
});
})(i)
}
Upvotes: 1