gpt4 book ai didi

jquery - 使用函数内的变量设置新变量

转载 作者:行者123 更新时间:2023-12-01 08:12:53 24 4
gpt4 key购买 nike

我正在使用地理定位创建一个网络应用程序。到目前为止,我已经设置并运行了它,因此当用户访问时,系统会提示他们允许位置服务,然后会显示一个警报(不是永久性的,仅用于测试目的。)

我正在使用这个:

navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy:true});

function foundLocation(position)
{
var lat = position.coords.latitude;
var long = position.coords.longitude;
alert('We know you are here '+ lat +','+ long);
}
function noLocation()
{
alert('Could not find location');
}

然后我在这个变量之外有一个名为“address”的变量,它是 API 调用的 URL:

address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/[LOCATION].json"

我的问题是如何从函数中获取 latlong 并将它们插入到 URL 中?我尝试了几种方法,但它们都返回“未定义”,所以我显然做错了什么。

非常感谢任何帮助!

谢谢。

最佳答案

您必须了解 javascript 变量的范围,请阅读这篇文章:What is the scope of variables in JavaScript?

var address = '';

function setLocation(position)
{
var lat = position.coords.latitude;
var long = position.coords.longitude;
address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/" + lat + "," + long + ".json";
}

此外,还有更好的方法来解决您的问题。最简单的方法是创建一个具有唯一名称的全局对象,将变量作为该对象的属性以及更改变量的方法,例如:

var geolocation = {};
geolocation.latitude = 0;
geolocation.longitude = 0;
geolocation.address = "";
geolocation.setLocation = function(position) {
geolocation.latitude = position.coords.latitude;
geolocation.longitude = position.coords.longitude;
geolocation.address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/" + geolocation.latitude + "," + geolocation.longitude + ".json";
};
geolocation.show = function() {
alert(geolocation.latitude + " " geolocation.longitude + " " + geolocation.address);
};

等等。现在,如果您使用文件中的任何地方:

geolocation.setLocation(position);
geolocation.show();

它将显示全局对象的新值。

更新

请记住,如果没有包装器,JavaScript 中的变量或对象将是全局的,就像另一个函数或对象一样。

关于jquery - 使用函数内的变量设置新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12409019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com