我定義了名爲「delka」和「sirka」的變量,我想在下面的函數中更改它們的值。顯然,我做錯了什麼,因爲當函數結束時,這些變量不會受到它的影響。爲什麼? Thx尋求答案。Javascript - 變量範圍
var sirka;
var delka;
var mestoNaLL = document.getElementById("mesto").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ "address": mestoNaLL }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
sirka = results[0].geometry.location.lat();
delka = results[0].geometry.location.lng();
} else {
alert("Chyba: " + status);
}
});
//undefined, why?
alert(mestoNaLL + " " + sirka + " " + delka + " ");
編輯
這裏也是同樣的問題,對不對?
//works fine
alert(markers[index].title + " " + infoWindows[index].content);
markers[index].addListener("click", function() {
//error - undefined
alert(markers[index].title + " " + infoWindows[index].content);
infoWindows[index].open(map, markers[index]);
map.setZoom(14);
map.setCenter(markers[index].getPosition());
});
由於地理編碼方法是做異步東西:http://stackoverflow.com/questions/14220321/how-do -i-return-the-an-asynchronous-call/14220323#14220323 –