为什么我的变量不取函数中的值

Why does my variables dont take the value in the function?

本文关键字:函数 我的 变量 为什么      更新时间:2023-09-26

我想在屏幕上显示var经度和纬度,但我认为函数是最后执行的,我被初始值卡住了。目标是在屏幕上打印浏览器返回的地理位置的精确值。谢谢

<!DOCTYPE html>

<head>
<script>
var longitude = "10";
var latitude = "20";
</script>


</head>
<html>
<body  onload="getLocation()">

<script>
var longitude = "30";
function getLocation() {
    if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position){
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
                alert('aaab:' +longitude);
    });
    }else {
                   alert("Geolocation API is not supported in your browser.");
    }
    }
</script>

<script>
alert("ccc");
document.write (longitude);
document.write (latitude);
</script>
</body>
</html>

我知道它在函数内工作,但有什么方法可以在函数外使用这些变量吗?我只想把它们存储在一个全局变量中,可以在任何地方调用。感谢

document.write在更新它的代码运行之前执行。您需要在回调中执行document.write,如下所示:

<!DOCTYPE html>
  <head>
    <script type='text/javascript'>
      var longitude = "10";
      var latitude = "20";
      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position){
            latitude = position.coords.latitude;
            longitude = position.coords.longitude;
            document.write(latitude+" / "+longitude);  
          });
        }else{
          alert("Geolocation API is not supported in your browser.");
        }
      }
    </script>
  </head>
  <body onload="getLocation()">
  </body>
  </html>

试试这个:

function getLocation() {
    if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(displayLocation);
    }else {
                   alert("Geolocation API is not supported in your browser.");
    }
}
    function displayLocation(position) {
       latitude = position.coords.latitude;
       longitude = position.coords.longitude;
       alert('aaab:' +longitude);
    }

在编写经度和纬度时,地理位置回调可能尚未调用。也许您可以使用jQuery将正确的值写入屏幕。。。

<script>
    var longitude = "30";
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position){
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
                //alert('aaab:' +longitude);
                // Use jQuery to write your values to the html
                $("#longitude").html(longitude);
                $("#latitude").html(latitude);
            });
        }else {
            alert("Geolocation API is not supported in your browser.");
        }
    }
</script>
<html>
    ...
    <body onload="getLocation()">
        <div id="longitude"></div>
        <div id="latitude"></div>
    </body>
</html>