[英]adding click to google maps api v3
I have an array of 7 marker points , I want to add a click handler to each marker. 我有7个标记点组成的数组,我想向每个标记添加点击处理程序。 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: googleMarkerPoints
的填充方式如下:
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 我的问题是,每次单击处理程序
selector
中的任何标记时,
"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?? 我希望每个标记从1到7的数据数都不同,为什么这些点击处理程序无法正常工作?
You are closing over i
and so you only get one value for all of the events. 您即将结束
i
,因此所有事件仅获得一个值。 Try passing the i
value into your anonymous function like this: 尝试将
i
值传递给您的匿名函数,如下所示:
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.