Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ES6模块:导入后未定义onclick函数_Javascript_Ecmascript 6_Es6 Modules - Fatal编程技术网

Javascript ES6模块:导入后未定义onclick函数

Javascript ES6模块:导入后未定义onclick函数,javascript,ecmascript-6,es6-modules,Javascript,Ecmascript 6,Es6 Modules,我正在测试ES6模块,想让用户使用onclick访问一些导入的函数: test.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Module Test</title> </head> <body> <input type="button" value="click me" onclick=

我正在测试ES6模块,想让用户使用
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>
当我单击按钮时,开发人员控制台显示:ReferenceError:hello未定义。如何从模块中导入函数,使它们可以作为onclick函数使用


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

模块创建一个作用域以避免名称冲突

将函数暴露于
窗口
对象

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

window.hello = hello
或者使用
addEventListener
绑定处理程序

点击我
从“./test.js”导入{hello}
document.querySelector(“#hello”).addEventListener('click',hello)
ES6中的模块范围模块: 使用
type=“module”
以以下方式导入脚本时:


你能在页面加载后打开控制台并手动执行hello吗?这个功能被标记为实验性的,我现在不会使用它。你最好对你的代码进行传输(Babel?),以确保它在任何浏览器中都能正常工作,不是吗?当然可以选择第二种。在最好的时候,全球化是一种痛苦。
import {hello} from './test.js'

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

  document.querySelector('#hello').addEventListener('click', hello)
</script>
<script type="module">import {hello} from "./test.js";</script>
window.hello = hello;  // putting the hello function as a property on the window object