javascript - JS 模块 - ReferenceError : <function> is not defined

标签 javascript html material-design referenceerror

我正在尝试使用“模块”类型从外部 .js 文件导入 js 函数,但我一直收到错误“ReferenceError:polygonClick 未定义”。

这是我的代码:

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); 
}

有人可以告诉我我做错了什么吗?

提前致谢!

最佳答案

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

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

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

关于javascript - JS 模块 - ReferenceError : <function> is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53268248/

相关文章:

android - 来自谷歌的新底部布局

html - Polymer.js 纸标签样式

javascript - 使用 MethodDecorator 更改函数的参数,而不更改 "this value"?

javascript - 创建滚动标记以显示网页中的重要位置

html - 如果 <h1> 中的内容始终保持不变而 <h2> 根据文章而变化,这对 SEO 是否合适?

html - IE9 只_有时_忽略 <base href>

php - 读取txt文件并解析文本

javascript - 自定义滚动用户体验

javascript - jquery p :last-child not working

android - 平板电脑和手机中抽屉导航的不同宽度