当我插入 x 的值而不是使用 for 循环时,这段代码有效。 但是当我使用 for 循环时,信息窗口在屏幕左侧显示失真。
什么脚跟!
for (var x = 0; x
var position = new google.maps.LatLng( data.events.event[x]['latitude'], data.events.event[x]['longitude']); marker.push( new google.maps.Marker({ position: position, map: map, icon: image} )); google.maps.event.addListener(marker[x], 'click', function() { infowindow.setContent(content[x]); infowindow.open(map, marker[x]); });
}
在这种情况下,您必须使用闭包。喜欢这个:
(function(m,c){
google.maps.event.addListener(m, 'click', function() {
infowindow.setContent(c);
infowindow.open(map, m);
});
})(marker[x],content[x])
实现
此目的的一种经济方法是使标记知道自己的索引,但代价是每个标记只有一个 Number 属性,并且避免需要形成一组包含content[x]
副本的闭包。
for (var x = 0; x < data.page_size; x++) {
...
marker[x].x = x;//make the marker aware of its own index
google.maps.event.addListener(marker[x], 'click', function() {
infowindow.setContent(content[this.x]);
infowindow.open(map, this);
});
}
如果marker
数组和content
数组保持静态或兼容管理,则this.x
将可靠地为每个标记提取正确的内容。