关于javascript:ES6模块”未捕获的ReferenceError:未在HTMLButtonElement.onclick上定义函数”

ES6 module “Uncaught ReferenceError: function is not defined at HTMLButtonElement.onclick”

我正在尝试使用谷歌浏览器中的ES6模块。我想在单击按钮时启动alert()(在导入的函数中)。

js / notification.js加载良好,但是当我单击按钮时出现错误:

Uncaught ReferenceError: createNotification is not defined
at HTMLButtonElement.onclick ((index):24) <- line of the button in index.html

index.html

1
2
3
4
5
6
7
8
<head>
    <script type="module" src="js/main.js">
</head>
<body>
    <section id="container">
       <button type="error" onclick="createNotification()">Create</button>
    </section>
</body>

js / main.js

1
import {createNotification} from './notification.js';

js / notification.js

1
2
3
export function createNotification(type){
    alert();
}


onxyz属性样式的处理程序中使用的

函数必须是全局变量(这是不使用它们的众多原因之一)。您的函数不是全局函数,对于要在其中导入模块而言是局部函数。 (请记住:您的主脚本也是模块;如果不是,则不能在其中使用import。)

您可以通过分配一个window属性使其成为全局变量:

1
window.createNotification = createNotification;

,但是使用现代事件处理会更好:

1
document.querySelector("#container button").addEventListener("click", createNotification);

plnkr上的实时示例,显然仅适用于支持模块的尖端浏览器。

旁注:正如Andreas指出的那样,type="error"button元素无效。有效类型为buttonsubmitreset,其中默认值为submit。 (我已在plnkr中将其更改为button。)