【发布时间】:2017-09-12 10:07:05
【问题描述】:
我使用浏览器的内置导航器创建了一个包含两个元素的数组。 gpsLocation[0] 是我的纬度,gpsLocation1 是我的经度。在我的 jQuery 代码之前,使用日志检查我的 gpsLocation,我确认这两个值都存在。然而,当我将数组的第一个元素分配给段落元素的 html 时,它显示未定义。我什至检查了它给我的坐标,它们非常准确。我已经搜索了答案,并且有一百万个类似措辞的问题,但似乎没有一个人试图这样做。
这是我的代码:
function getLocation() {
var gpsLocation = [];
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
gpsLocation.push(position.coords.latitude);
gpsLocation.push(position.coords.longitude);
});
}
return gpsLocation;
}
function getWeather() {
var gpsLocation = getLocation();
console.log(gpsLocation);//Looks good in the console.
$(function(){
$('#test-paragraph').html('Latitude: ' + gpsLocation[0]);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather">
<button id="test-button" onclick="getWeather()">Test Button</button>
<p id="test-paragraph">This is a sample paragraph for learning jQuery</p>
</div>
第二个函数名称可能看起来很随意,但天气最终将是它的目的。仍然在努力理解 jQuery 和 json。
【问题讨论】:
-
我看不到
console.log(gpsLocation);的任何输出。当我运行你的代码时。向我们展示你从中得到了什么输出。 -
getCurrentPosition()是异步的,可能是 How do I return the response from an asynchronous call? 的欺骗 -
我添加了一张我在控制台中看到的图片。当然被黑了,不希望你们中的任何一个人出现在我家进行私人演讲。
-
所以我在该链接中阅读了答案。我并没有声称自己理解其中的任何内容,但根据他的电话类比,我想如果这里发生这种情况,console.log 也不会知道 gpsLocation 中的内容,对吧?
标签: javascript jquery html arrays