[英]Can't change value of global variable JS
我有2個全局變量:Lon和Lat並且我想在HTML5提供的地理定位功能內更改這些變量的值:這是我的代碼:
window.lat={{geo['latitude']}};
window.lon={{geo['longitude']}};
var SK= readCookie('SK');
if(SK==1)
{
navigator.geolocation.getCurrentPosition(function(e){
window.lat=e.coords.latitude;
window.lon=e.coords.longitude;
window.zoomi=15;
})
}
window .lat的最終值始終是
window.lat={{geo['latitude']}}
有人知道為什么嗎?
PS:SK == 1是正確的,並且在函數(e)中,我試圖提醒這些值,並且它們確實發生了變化。 但是一旦功能失效,一切都會消失
Javascript始終是同步的並且是單線程的,因此如果您在回調后檢查window.lat,即使在gelocation調用之前它也已執行並且它具有相同的值,geolocation需要幾秒鍾的時間才能獲取該值,因此您必須在回調函數中編寫代碼編寫函數以使用地理定位值。
window.lat=1;
window.lon=3;
var SK= 1
if(SK==1)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
//anything written here will be executed before even the getCurrentPosition retuns or sets the results
function showPosition(position)
{
alert("Latitude: " + position.coords.latitude + "-Longitude: " + position.coords.longitude);
//write your code here to use the location
}
這是jsfiddle http://jsfiddle.net/Xa64Q/,解釋了問題,如果我們在幾秒鍾后運行警報,它將返回正確的值
使用調試器(例如Chrome開發者工具或Firefox的Firebug)逐步進行調試。 該代碼有效並且在原理上相同。 對於這種變量分配,它工作得很好:
window.x = 1;
function change() {
window.x = 2;
}
change();
alert(window.x);
我的猜測是getCurrentPosition
調用突然失敗。 順便說一句,該調用需要一個錯誤回調處理程序,因此您應該為代碼定義一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.