将变量保存在navigator.geolocation.getCurrentPosition之外? (JavaScript的) [英] Saving variables outside of navigator.geolocation.getCurrentPosition? (javascript)
本文介绍了将变量保存在navigator.geolocation.getCurrentPosition之外? (JavaScript的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用js的范围来将一个变量从navigator.geolocation.getCurrentPosition中取出
I'm trying to play with the scope of js to pull a variable out of navigator.geolocation.getCurrentPosition
var lat;
function callback (position) {
lat = position.coords.latitude;
}
navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
// after getCurrentPosition succeeds
alert(lat); // this alerts null
上面的代码不能在lat变量中存储position.coords.latitude,因为范围。有没有办法做到这一点?
The above code cannot store position.coords.latitude in the lat variable because of the scope. Is there a way to do this?
推荐答案
您必须记住async \ ajax性质。
You have to remember the async\ajax nature.
这是您的代码的执行顺序:
this is the execution order of your code:
var lat;
alert(lat); // this alerts null
navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
function callback (position) {
lat = position.coords.latitude;
}
这就是为什么你会得到空值的原因。 异步!,异步!:)
This why you get null. async!, async! :)
这篇关于将变量保存在navigator.geolocation.getCurrentPosition之外? (JavaScript的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文