我正在尝试使用“模块”类型从外部 .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/