我正在设置一个 HTML5 GeoLocation 脚本,我想将邮政编码存储在 cookie 中,但现在我只是想弄清楚如何将邮政编码变量传递到另一个函数中。
这是我根据纬度/经度反转地理代码的脚本:
function retrieve_zip(callback)
{
try { if(!google) { google = 0; } } catch(err) { google = 0; } // Stupid Exceptions
if(navigator.geolocation) // FireFox/HTML5 GeoLocation
{
navigator.geolocation.getCurrentPosition(function(position)
{
zip_from_latlng(position.coords.latitude,position.coords.longitude,callback);
});
}
else if(google && google.gears) // Google Gears GeoLocation
{
var geloc = google.gears.factory.create('beta.geolocation');
geloc.getPermission();
geloc.getCurrentPosition(function(position)
{
zip_from_latlng(position.latitude,position.longitude,callback);
},function(err){});
}
}
function zip_from_latlng(latitude,longitude,callback)
{
// Setup the Script using Geonames.org's WebService
var script = document.createElement("script");
script.src = "http://ws.geonames.org/findNearbyPostalCodesJSON?lat=" + latitude + "&lng=" + longitude + "&callback=" + callback;
console.log(script.src);
// Run the Script
document.getElementsByTagName("head")[0].appendChild(script);
}
function callback(json)
{
zip = json.postalCodes[0].postalCode;
country = json.postalCodes[0].countryCode;
state = json.postalCodes[0].adminName1;
county = json.postalCodes[0].adminName2;
place = json.postalCodes[0].placeName;
alert(zip);
}
$('#findLocation').click(function(event) {
event.preventDefault();
console.log(zip); // This is giving me undefined currently
});
所以基本上,在回调函数中,我想将邮政编码存储为变量(而不是将其显示在警报中),然后在底部的 on click
函数中,我想要能够显示存储在上一个回调函数中的邮政编码。
非常感谢任何帮助,对于 Javscript/jQuery 来说仍然很新,谢谢!
最佳答案
您可以将 zip
设置为“全局”变量,方法是将其包含在文档顶部的函数之外,如下所示:
var zip;
...
或者,您可以考虑在“全局”级别定义一个对象,并将其用作命名空间来存储变量,如下所示:
window.address = {};
function callback(json){
address.zip = json.postalCodes[0].postalCode;
address.country = json.postalCodes[0].countryCode;
address.state = json.postalCodes[0].adminName1;
address.county = json.postalCodes[0].adminName2;
address.place = json.postalCodes[0].placeName;
}
$('#findLocation').click(function(event) {
event.preventDefault();
console.log(address.address);
console.log(address.zip);
...
});
希望这会有所帮助!
关于javascript - 将变量从回调函数传递到另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23398322/