全局var在函数外部是未定义的,Javascript

时间:2017-04-16 12:52:19

标签: javascript variables

我试图将函数内部的变量存储到全局变量中。

但是函数之外的全局变量仍未定义。

代码段:

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

我也希望在函数之外使用变量,我该如何解决这个问题呢?

1 个答案:

答案 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>