首页 > 解决方案 > 我在 JavaScript 文件顶部设置的“全局”变量无法被文件内更下方的函数访问

问题描述

我有一个显示天气的页面。

我调用 Wea​​therbit.io API 来获取信息。他们需要的部分信息是该位置的纬度和经度。

出于某种原因,lat_lon我在我的 JavaScript 文件开头设置的变量对于我在文件中进一步向下的某些函数是不可访问的。每当我尝试使用它时,我都会不断收到“ undefined”错误。

索引.html:

<head>
    <script type="text/javascript" src="./JavaScript.js"></script>
</head>
<body onload="startup();">
    ...
</body>

JavaScript.js:

var lat_lon = "lat=37.600000&lon=-95.665047";

function startup(){
    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position){
            lat_lon = "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude;
            console.log("FIRST: " + lat_lon);
        });
    }
    console.log("SECOND: " + lat_lon);

    weatherFunctionCurrent(lat_lon);
    weatherIntervalVarCurrent = setInterval(weatherFunctionCurrent, 600000);
}

// .
// .
// .

weatherFunctionCurrent(lat_lon){
    console.log("IN THE weatherFunctionCurrent FUNCTION: " + lat_lon);
}

说我的实际纬度/经度是: lat=123.4 和 lon=-123.4

第二:lat=37.600000&lon=-95.665047
在 weatherFunctionCurrent 函数中:lat=37.600000&lon=-95.665047
第一:lat=123.4&lon=-123.4
在 weatherFunctionCurrent 函数中:未定义
在 weatherFunctionCurrent 函数中:未定义
在 weatherFunctionCurrent 函数中:未定义
在 weatherFunctionCurrent 函数中:未定义
.
.
.

我试过var window.lat_lon = ""了,但 Chrome 不喜欢这样。我收到了错误

未捕获的语法错误:意外的标记“。”

我究竟做错了什么?

标签: javascripthtmlgeolocation

解决方案


传递lat_ton给你的函数:

weatherIntervalVarCurrent = setInterval(weatherFunctionCurrent(lat_lon), 600000);

推荐阅读