ES6 模块:导入后未定义的 onclick 函数 [英] ES6 Modules: Undefined onclick function after import
问题描述
我正在测试 ES6 模块,并希望让用户使用 onclick
访问一些导入的函数:
I am testing ES6 Modules and want to let the user access some imported functions using onclick
:
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 is not defined.如何从模块中导入函数,以便它们可用作 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?
我使用的是 Firefox 54.0,dom.moduleScripts.enabled
设置为 true
.
I am using Firefox 54.0 with dom.moduleScripts.enabled
set to true
.
推荐答案
模块创建一个作用域来避免名称冲突.
Module creates a scope to avoid name collisions.
要么将你的函数暴露给 window
对象
Either expose your function to window
object
import {hello} from './test.js'
window.hello = hello
或者使用addEventListener
来绑定handler.演示
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屋!