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

编程入门 行业动态 更新时间:2024-10-28 18:26:07
本文介绍了ES6模块“Uncaught ReferenceError:函数未在HTMLButtonElement.onclick”中定义。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在谷歌浏览器中尝试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”中定义。

本文发布于:2023-11-23 03:42:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   模块   定义   Uncaught   onclick

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!