繁体   English   中英

无法更改全局变量JS的值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM