我是 ES6 模块的新手,请告诉我如何从网页上的 ES6 模块导入函数,然后在按钮的单击事件上使用该函数。
到目前为止,我已在名为 (ES6Part3Module.js) 的文件中定义了此模块:
export function sayHello() {
return "hi there folks";
}
然后在我的 html 页面中,我以这种方式加载模块:
`<script src="ES6Part3Module.js" type="module"`>`</script`>
我现在想要某种方法为页面上的按钮创建点击处理程序:
`<button id="sayHelloButton"`>Say Hello`</click`>
它从我的 ES6 模块调用 sayHello() 函数。
我尝试在我的页面上创建本地(模块)脚本:
`<script type="module"`>
import sayHello from "ES6Part3Module.js";
window.hello = sayHello;
`</script`>
然后在页面上加载一些jquery:
$( function() {
$("#sayHelloButton").click(function() {
alert(hello());
});
});
但是当单击 html 页面上的按钮时,出现错误,提示 hello 未定义。
请让我知道我做错了什么?
最佳答案
这是使用旧版本的 system.js 的答案。我对使用新版本的 system.js 的答案感兴趣。
<!--
ref (https://livebook.manning.com/#!/book/angular-2-development-with-typescript/chapter-2/159, p 159, listing2.7)
-->
<!--unpkg is a fast, global content delivery network for everything on npm-->
<script src="//unpkg.com/es6-promise@3.0.2/dist/es6-promise.js"></script>
<script src="//unpkg.com/traceur@0.0.111/bin/traceur.js"></script>
<!--system js, version that was released in 21/08/2016-->
<script src="//unpkg.com/systemjs@0.19.37/dist/system.src.js"></script>
<script>
System.import('./ES6Part3Module.js').then(ES6Part3Module => {
window.hello = ES6Part3Module.sayHello;
});
</script>
<script>
$( function() {
$("#sayHelloButton").click(function() {
alert(hello());
});
});
</script>
关于javascript - 如何在加载事件中加载 html 页面中的 es6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46809853/