我试图将函数内部的变量存储到全局变量中。
但是函数之外的全局变量仍未定义。
代码段:
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
var latitude;
var longitude;
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
latitude = position.coords.latitude
longitude = position.coords.longitude
console.log(longitude); // var longitude is set here
}
console.log(longitude); // var longitude is undefined here
我也希望在函数之外使用变量,我该如何解决这个问题呢?
答案 0 :(得分:-1)
参考此代码
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude +" Longitude: " + position.coords.longitude)
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>