Javascript意外运行顺序
下面是jquery/javascript代码。它向用户请求位置权限,然后输出一个URL字符串,并在末尾附加纬度 我放置了3个console.log statemnets来突出显示问题,以及我得到的当前输出 预期调试值(按顺序) 1_lat=95.5555 2_lat=95.5555 三,_https://fcc-weather-api.glitch.me/api/current?&lat=95.555555 实际调试值:(按顺序) 二,_ 三,_https://fcc-weather-api.glitch.me/api/current?& 1_lat=95.5555Javascript意外运行顺序,javascript,jquery,Javascript,Jquery,下面是jquery/javascript代码。它向用户请求位置权限,然后输出一个URL字符串,并在末尾附加纬度 我放置了3个console.log statemnets来突出显示问题,以及我得到的当前输出 预期调试值(按顺序) 1_lat=95.5555 2_lat=95.5555 三,_https://fcc-weather-api.glitch.me/api/current?&lat=95.555555 实际调试值:(按顺序) 二,_ 三,_https://fcc-weather-api.g
我一定不了解javascript是如何加载的,jQuery document.ready.function是如何影响结果的。
navigator.geolocation
是异步的。因此,您必须等待navigator.geolocation.getCurrentPosition
回调函数,然后才能处理lat
和lng
您可以这样做:
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
}
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
这将导致:
1_ lat=1.xxx
2_ lat=1.xxx
3_ https://fcc-weather-api.glitch.me/api/current?&lat=1.xxx
你怎么知道navigator.geolocation是异步的?你是什么意思?默认情况下javascript不是单线程和同步的,你怎么知道使用navigator.geolocation是异步的?我怎么知道?此外,你可以知道,关于它的行为,网上有很多文件都这么说。
1_ lat=1.xxx
2_ lat=1.xxx
3_ https://fcc-weather-api.glitch.me/api/current?&lat=1.xxx