我正在谷歌浏览器中尝试ES6模块。当我点击按钮时,我想启动一个alert()(在导入的函数中)。
I am trying ES6 module in google chrome. I would like to launch an alert() (in an imported function) when i click on the button.
js / notification.js装载得很好但是当我点击时按钮我收到错误:
js/notification.js is well loaded but when I click on the button I get an error:
未捕获的ReferenceError:未定义createNotification HTMLButtonElement.onclick((index):24 )< - index.html中的按钮行
Uncaught ReferenceError: createNotification is not defined at HTMLButtonElement.onclick ((index):24) <- line of the button in index.html
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>js / main.js
js/main.js
import {createNotification} from './notification.js';js / notification.js
js/notification.js
export function createNotification(type){ alert(); }推荐答案
onxyz -attribute-style处理程序必须是全局变量(这是不使用它们的众多原因之一)。您的功能不是全局的,它是您导入它的模块的本地功能。 (请记住:你的主要脚本也是一个模块;如果不是,你就不能在其中使用 import 。)
Functions used in onxyz-attribute-style handlers must be globals (it's one of the many reasons not to use them). Your function isn't a global, it's local to the module in which you're importing it. (Remember: Your main script is a module too; if it weren't, you couldn't use import in it.)
您可以通过分配到窗口
You could make it a global by assigning to a window property:
window.createNotification = createNotification;但使用现代事件处理会更好 :
but it would be much better to use modern event handling:
document.querySelector("#container button").addEventListener("click", createNotification);plnkr上的实例,显然只适用于支持模块的尖端浏览器。
Live example on plnkr, obviously will only work on cutting-edge browsers with module support.
附注:由于 Andreas指出, type =error对按钮元素无效。有效类型为按钮,提交或重置, 提交作为默认值。 (我在plnkr中将其更改为按钮。)
Side note: As Andreas points out, type="error" isn't valid for button elements. Valid types are button, submit, or reset, with submit being the default. (I've changed it to button in the plnkr.)
更多推荐
ES6模块“Uncaught ReferenceError:函数未在HTMLButtonElement.onclick”中定义。
发布评论