简体   繁体   English

无法更改全局变量JS的值

[英]Can't change value of global variable JS

I have 2 global variables : Lon and Lat And I want to change the value of these variables inside the function of geolocalisation offered by HTML5: here is my code : 我有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;
    })
}

the final value of window .lat is always window .lat的最终值始终是

window.lat={{geo['latitude']}}

Does anyone know why ? 有人知道为什么吗?

PS: the SK==1 is true, and inside the function(e), I tried to alert the values and they really change. PS:SK == 1是正确的,并且在函数(e)中,我试图提醒这些值,并且它们确实发生了变化。 but once out of the function, everything vanishes 但是一旦功能失效,一切都会消失

Javascript is always synchronous and single-threaded so if you are checking window.lat after callback it gets executed even before gelocation call and it has same value.geolocation takes few seconds to get the value and you must write up your code in callback fucntion or write a function to use geolcoation values. 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 
} 

here is the jsfiddle http://jsfiddle.net/Xa64Q/ explaining the issue if we are running alert after few seconds it returns correct value 这是jsfiddle http://jsfiddle.net/Xa64Q/,解释了问题,如果我们在几秒钟后运行警报,它将返回正确的值

Step through it with a debugger (like Chrome dev tools or Firebug for Firefox). 使用调试器(例如Chrome开发者工具或Firefox的Firebug)逐步进行调试。 This code works and is the same in principle. 该代码有效并且在原理上相同。 It works just fine for this sort of variable assignment: 对于这种变量分配,它工作得很好:

window.x = 1;
function change() {
 window.x = 2;   
}
change();
alert(window.x);

My guess is that the getCurrentPosition call is abruptly failing. 我的猜测是getCurrentPosition调用突然失败。 BTW, that call takes an error call back handler so you should define one for your code. 顺便说一句,该调用需要一个错误回调处理程序,因此您应该为代码定义一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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