为什么我的变量不采用函数中的值? [英] Why does my variables dont take the value in the function?

查看:94
本文介绍了为什么我的变量不采用函数中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在屏幕上显示var longitude en latitude,但我认为该函数最后执行,并且我坚持使用初始值。
目标是在屏幕上显示浏览器返回的地理位置的确切值。
Thanks !!!

I want to display on screen the var longitude en latitude but I think that the function is executing last and I'am stuck with the initial values. The objective is to print on screen the exact values of the geolocation that the browser returns. Thanks !!!

<!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>

我知道它在函数内部工作,但有什么办法可以在外部使用这些变量?我只是希望能够将它们存储在一个可以在任何地方被调用的全局变量中。谢谢

i know that it's working within the function, but there is any way to use those variable outside? I just want to be able to store them in one global variable that cand be called wherever. Thanks

推荐答案

<!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>

这篇关于为什么我的变量不采用函数中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆