[英]Can an argument in a custom jquery function change the value of a global variable
[英]Can not use global variable as argument for jQuery function
我正在嘗試使用API顯示當地天氣。 API網址會根據用戶的本地位置生成。
var lat,lon = null;
var key = "mykey";
var api = "";
function setApi(position){
lat = Math.round(position.coords.latitude*1000)/1000;
lon = Math.round(position.coords.longitude*1000)/1000;
api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + key;
}
navigator.geolocation.getCurrentPosition(setApi);
$.getJSON(api, function(data){
console.log(data.sys.country);
});
如果我使用我的api全局變量作為$ .getJSON函數的參數,問題就不會發生。 如果我使用字符串代替它。 例如:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=46.295&lon=30.648&appid=%mykey%", function(data){
console.log(data.sys.country);
});
我相信你遇到的問題是,在調用$.getJSON
,實際的api
值仍設置為""
。
這很可能是由getCurrentPosition
的異步操作引起的。 這意味着$.getJSON
在setApi
回調函數之前被有效地調用。
我建議根據您當前的代碼,最簡單的解決方案是在setApi
函數中移動$.getJSON
調用,這樣您就可以確保只在正確設置api
值后調用它。
例如:
var lat,lon = null;
var key = "mykey";
var api = "";
function setApi(position){
lat = Math.round(position.coords.latitude*1000)/1000;
lon = Math.round(position.coords.longitude*1000)/1000;
api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + key;
$.getJSON(api, function(data){
console.log(data.sys.country);
});
}
navigator.geolocation.getCurrentPosition(setApi);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.