【问题标题】:function not defined javascript onclick [duplicate]函数未定义javascript onclick [重复]
【发布时间】: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:&nbsp;
             <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


【解决方案1】:

当您使用&lt;script type="module"&gt; 时,会创建一个单独的范围以防止名称冲突。详情请见JavaScript modules

您可以通过将函数添加到 window 命名空间来使其成为全局函数,如下所示:

window.area = area;

或者您可以在 JavaScript 中简单地使用 addEventListener

document.querySelector('[type=submit]').addEventListener('click', area);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2013-06-26
    • 2014-03-05
    • 2022-01-10
    相关资源
    最近更新 更多