ES6模块:导入后未定义的onclick功能 [英] ES6 Modules: Undefined onclick function after import

查看:370
本文介绍了ES6模块:导入后未定义的onclick功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试ES6模块,并希望让用户使用 onclick 访问一些导入的函数:

I am testing ES6 Modules and want to let the user access some imported functions using onclick:

test .html:

test.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Module Test</title>
</head>
<body>
    <input type="button" value="click me" onclick="hello();"/>
    <script type="module">import {hello} from "./test.js";</script>
</body>
</html>

test.js:

export function hello() {console.log("hello");}

当我单击按钮时,开发人员控制台会说: ReferenceError:未定义hello 。如何从模块导入函数以便它们可用作onclick函数?

When I click the button, the developer console says: ReferenceError: hello is not defined. How can I import functions from modules so that they are available as onclick functions?

我使用的是带有 dom.moduleScripts.enabled的Firefox 54.0 设置为 true

I am using Firefox 54.0 with dom.moduleScripts.enabled set to true.

推荐答案

模块创建一个避免名称冲突的范围。

Module creates a scope to avoid name collisions.

将您的函数暴露给窗口 object

Either expose your function to window object

import {hello} from './test.js'

window.hello = hello

或者使用 addEventListener 来绑定处理程序。 演示

Or use addEventListener to bind handler. Demo

<button type="button" id="hello">Click Me</button>
<script type="module">
  import {hello} from './test.js'

  document.querySelector('#hello').addEventListener('click', hello)
</script>

这篇关于ES6模块:导入后未定义的onclick功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆