我有一些代码如下,它获取当前位置,然后用该信息创建一个变量。我想在函数之外使用该变量,但到目前为止我尝试的一切都失败了。如果它在函数内,下面的警告会起作用,但一旦你把它放在外面,它就会变成空白。我也试过在 alloy.js 中创建全局变量,但这似乎也没有用。我知道这很简单,但需要更多想法 :)
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
alert('Error: ' + e.error);
} else {
var params = {
latitude: e.coords.latitude,
};
return params;
}
});
alert(params);
最佳答案
这与 Titanum 无关,而是一个基本的 javascript 问题。
params
是一个局部变量(在 getCurrentPosition 内)。您可以像这样创建一个全局范围:
var coords;
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
alert('Error: ' + e.error);
} else {
coords = {
latitude: e.coords.latitude,
longitude: e.coords.longitude,
};
}
});
但请记住:坐标可能不会立即设置,因为在 getCurrentPosition 函数完成或拥有数据之前可能需要一些时间。
关于javascript - Appcelerator/Titanium - 从函数内调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37440048/