【问题标题】:How to call javascript functions inside a <script type="module"> from HTML element events?如何从 HTML 元素事件中调用 <script type="module"> 中的 javascript 函数?
【发布时间】:2020-01-11 06:18:27
【问题描述】:

我有一个简单的 HTML 页面,它正在导入一个 JS 模块,如下所示:

.. snip
<button onclick="btnClick()">Go!</button>

<script type="module">
import { func1 } from './utils.js'

function btnClick() {
   func1()
}
</script>

单击按钮会产生错误:未定义 btnClick()。

为什么会这样?如何将这些功能带回到正确的范围内?

【问题讨论】:

标签: javascript import scope


【解决方案1】:

javascript 执行堆栈有自己的范围,因此,简单易用的解决方案是,您可以将您可访问的函数分配给窗口范围,如下所示;

<button onclick="btnClick()">Go!</button>

<script type="module">
    import { func1 } from './utils.js'

    function btnClick() {
      func1()
    }

    // variable function
    window.btnClick = btnClick;

    // or anonymous function
    window.btnClick = function(youCanSetParams){
      func1()
    }
</script>

【讨论】:

  • 如果您有多个功能,请执行window._myFns = { btnClick, onLoad }之类的操作
【解决方案2】:

“模块”中的变量无法从外部访问,因此请使用 type="text/javascript" as

<script type="text/javascript">

function btnClick() {
   console.log('here')
}
</script>
<button onclick="btnClick()">Go!</button>

【讨论】:

【解决方案3】:

当脚本是模块类型时,它只能监听事件,你不能从 html 调用函数, 所以你可以在点击事件中添加一个EventListener,检查调用dispatch事件的目标元素的id,然后调用函数:

<script type="module">
    import { func1 } from './utils.js'
    window.addEventListener('click' , e=> {
        switch(e.target.id){
           case 'btnGo':
             btnClick();
             break;
        }
    })
    function btnClick() {
       func1()
    }
</script>

<html>
    <button id="btnGo">Go!</button>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    相关资源
    最近更新 更多