我的代码
//执行ajax请求并获取JSON响应
for (var i = 0; i < data.results.length; i++) {
result = data.results[i];
// do stuff and create google maps marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(result.lat, result.lng),
map: map,
id: result.id
});
google.maps.event.addListener(marker, 'click', function() {
createWindow(marker.id); //<==== this doesn't work because marker always points to the last results when this function is called
});
}
如何解决这个问题?
答案 0 :(得分:24)
试试这个:
with ({ mark: marker }) {
google.maps.event.addListener(mark, 'click', function() {
createWindow(mark.id);
});
}
演示使用with
:
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 1000);
}
上述内容将记录10
十次。
for (var i = 0; i < 10; i++) {
with ({ foo: i }) {
setTimeout(function() { console.log(foo); }, 1000);
}
}
由于0
引入了新范围,因此会根据需要将9
记录到with
。
JavaScript 1.7有一个更好的let
语句,但在广泛支持之前,您可以使用with
。
并使用var
作为变量。
答案 1 :(得分:4)
google.maps.event.addListener(marker, 'click', function(id) {
return function(){
createWindow(id); //<==== this doesn't work because marker always points to the last results when this function is called
}
}(marker.id));
答案 2 :(得分:1)
看起来你有一个关闭问题。看到这些问题:
答案 3 :(得分:1)
尝试这个
var marker = new Array();
for (var i = 0; i < data.results.length; i++) {
result = data.results[i];
// do stuff and create google maps marker
marker[i] = new google.maps.Marker({
position: new google.maps.LatLng(result.lat, result.lng),
map: map,
id: result.id
});
google.maps.event.addListener(marker[i], 'click', example(marker[i].id));
}
创建新功能
function example(my_window){
return function(){
createWindow(my_window);
}
}