本文介紹了在 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
上面的代碼因為作用域的原因,不能將 position.coords.latitude 存儲在 lat 變量中.有沒有辦法做到這一點?
The above code cannot store position.coords.latitude in the lat variable because of the scope. Is there a way to do this?
推薦答案
你必須記住 asyncajax 的本質(zhì).
You have to remember the asyncajax nature.
這是你的代碼的執(zhí)行順序:
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;
}
這就是你得到 null 的原因.異步!,異步! :)
This why you get null. async!, async! :)
這篇關于在 navigator.geolocation.getCurrentPosition 之外保存變量?(javascript)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!