ES6模块“ Uncaught ReferenceError:在HTMLButtonElement.onclick中未定义函数”

art*_*boy 4 javascript ecmascript-6

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

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

未捕获的ReferenceError:在HTMLButtonElement.onclick((index :: 24)<-index.html中按钮的行

index.html

<head>
    <script type="module" src="js/main.js"></script>
</head>
<body>
    <section id="container">
       <button type="error" onclick="createNotification()">Create</button>
    </section>
</body>
Run Code Online (Sandbox Code Playgroud)

js / main.js

import {createNotification} from './notification.js';
Run Code Online (Sandbox Code Playgroud)

js / notification.js

export function createNotification(type){
    alert();
}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

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

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

window.createNotification = createNotification;
Run Code Online (Sandbox Code Playgroud)

但它会更好地使用现代的事件处理:

document.querySelector("#container button").addEventListener("click", createNotification);
Run Code Online (Sandbox Code Playgroud)

在plnkr上的实时示例显然只能在支持模块的尖端浏览器上使用。


旁注:正如Andreas指出type="error"不适用于button元素。有效类型为buttonsubmitresetsubmit并且为默认类型。(我将其更改button为plnkr。)