我的代码
//进行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
});
}
如何解决?
最佳答案
试试这个:
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
作为您的变量。
关于javascript - 将参数传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663309/