【问题标题】:How to load an es6 module in an html page on the load event如何在加载事件的html页面中加载es6模块
【发布时间】:2017-10-18 12:09:45
【问题描述】:

我是 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。

请你告诉我我做错了什么?

【问题讨论】:

    标签: javascript es6-modules


    【解决方案1】:

    这是使用旧版本 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>
    

    【讨论】:

      【解决方案2】:

      您实际上非常接近解决方案。
      在你 setwindow.hello=sayHello; 之后(你可以在你的模块中做,你不需要一个内联模块来做),你只需将按钮的点击事件设置为 window.hello (而不仅仅是你好),你不需要甚至需要为此使用 JQuery,您可以这样做:

      <button onclick="window.hello()">Say Hello</button>
      

      【讨论】:

        猜你喜欢
        • 2014-09-15
        • 2016-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-21
        相关资源
        最近更新 更多