【发布时间】:2020-07-08 20:00:37
【问题描述】:
如何通过 onclick 或 普通 JavaScript 从模块 JavaScript 文件调用函数。
在下面的代码中,单击按钮会引发“exampleFunction is not defined”异常(使用最新的 FireFox 版本进行测试并希望与现代浏览器兼容)
exampleModule.js
export function exampleFunction(){
alert('example Function');
}
examplePage.html
<html>
<head>
<script src="exampleModule.js" type="module"></script>
</head>
<body>
<button onclick="exampleFunction();">button</button>
</body>
</html>
【问题讨论】:
-
使用前需要将脚本导入文件。
-
这里只导入函数我们有同样的问题stackoverflow.com/questions/49338193/…
-
并且您需要将函数分配给全局对象 (
window),以便您可以使用属性中的exampleFunction();。你也可以使用addEventListener()。 -
你会在这里找到答案 --> stackoverflow.com/questions/49338193/…
标签: javascript