【发布时间】:2019-09-15 09:50:39
【问题描述】:
我是编程新手,所以不要评判我。尝试编写代码来测量经纬度的长度。它显示此错误:
length.html:27 Uncaught ReferenceError: area is not defined 在 HTMLInputElement.onclick (length.html:27)
<html>
<head></head>
<body>
<script type="module">
import LatLon from 'https://cdn.jsdelivr.net/npm/geodesy@2.2.0/latlon-spherical.min.js';
function area()
{
var la1 = document.getElementById(lat1).value;
var la2 = document.getElementById(lat2).value;
var lo1 = document.getElementById(lon1).value;
var lo2 = document.getElementById(lon2).value;
const p1 = new LatLon(la1, lo1);
const p2 = new LatLon(la2, la2);
const d = p1.distanceTo(p2);
document.write('<br>Length is : ' + d);
}
</script>
<form>
First point<br>
Latitude:
<input type="text" name="lat1" id="lat1"><br>
Longitude:
<input type="text" name="lon1" id="lon1"><br>
Second point<br>
Latitude<input type="text" name="lat2" id="lat2"><br>
Longitude<input type="text" name="lon2" id="lon2"><br>
<input type="button" value="submit" onclick="area()">
</form>
</body>
</html>
【问题讨论】:
-
在你的 body 标签结束之前编写你的函数
-
查看链接问题的答案。基本上,您从
onxyz-attribute-style 事件处理程序调用的函数必须是全局的,但您的area不是全局的,因为您的脚本是一个模块,并且是顶级的模块中的声明不是全局的(它们只能在模块内访问)。相反,使用现代技术来连接你的处理程序:获取元素引用,然后使用addEventListener。 -
您的脚本在页面其余部分之前加载。搜索“如何加载 HTML”或“放置脚本标记的位置”,或查看此答案 - stackoverflow.com/questions/8996852/…>
-
@AndrewShymanel - 模块会自动延迟(生效),请参阅here 并向下滚动到显示脚本何时以及如何加载和执行的图形。
-
@T.J.Crowder 你说得对,谢谢
标签: javascript