【问题标题】:JS modules - ReferenceError: <function> is not definedJS 模块 - ReferenceError: <function> 未定义
【发布时间】:2019-04-15 12:47:53
【问题描述】:

我正在尝试使用“模块”类型从外部 .js 文件导入 js 函数,但我不断收到错误消息“ReferenceError: polygonClick is not defined”。

这是我的代码:

HTML:

<!DOCTYPE html>
<html>
  <head>
    ...
    <script src="js/map.js" type="module"></script>
  </head>
  <body>
    ...
    <script>
      function initMap() {
        ...
        $.getJSON( "./DI.json", function( coords ) {
            var building = new google.maps.Polygon({...});
            building.setMap(map);

            building.addListener('click', (event) => polygonClick(event));
        });
        ...
      }
    </script>
  </body>
</html>

JS:

import {MDCDrawer} from './@material/drawer';

export default { polygonClick };

const drawer = MDCDrawer.attachTo(document.querySelector('.mdc-drawer'));

function polygonClick(event) {
    console.log(event); 
}

谁能告诉我我做错了什么?

提前谢谢你!

【问题讨论】:

  • 将您的第二个脚本也设为module,并从第一个脚本导入polygonClick 函数。否则它将停留在模块的范围内 - 与普通脚本不同,模块代码不会在全局范围内运行。
  • @Bergi 你将什么定义为我的第二个脚本?整个initMap 函数?
  • 是的,那个脚本。虽然不清楚你从哪里打电话给initMap。

标签: javascript html material-design referenceerror


【解决方案1】:

是因为你的module里面的js代码不是全局的,所以函数initMap()不是全局的。 Simpy,以这种方式使其全球化:

window.polygonClick = function(event){
    //you function code
}

窗户。将使变量或函数在上下文中成为全局变量。

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 2023-03-20
    • 2016-02-28
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多