javascript - 我在 JavaScript 文件顶部设置的“全局”变量无法被文件内更下方的函数访问
问题描述
我有一个显示天气的页面。
我调用 Weatherbit.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 不喜欢这样。我收到了错误
未捕获的语法错误:意外的标记“。”
我究竟做错了什么?
解决方案
传递lat_ton
给你的函数:
weatherIntervalVarCurrent = setInterval(weatherFunctionCurrent(lat_lon), 600000);
推荐阅读
- c# - 从数据表中获取单元格
- angular - 如何使用 Angular 8 修复滚动标题?
- android - 是否可以在仪器测试中将启用设置为 ConstraintLayout?
- c# - 如何修复丢失的 vcruntime140 clr 400 dll 错误
- python - Numba cuda:使用共享内存添加数字会导致覆盖
- c# - 如何使用 System.Management.Automation
- git - Git无法解析交互式rebase上的“reword”命令
- javascript - 使用上下文映射鼠标坐标
- html - 如何使用两个条件动作制作 Haml 表单
- javascript - 输入框计算器不会改变结果值