我是 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/[email protected]/dist/es6-promise.js"></script>
<script src="//unpkg.com/[email protected]/bin/traceur.js"></script>
<!--system js, version that was released in 21/08/2016-->
<script src="//unpkg.com/[email protected]/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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句