繁体   English   中英

如何从 html onclick 中的 javascript 模块调用函数

[英]How can I call a function from javascript module in html onclick

 <h1 onclick="sayhello()"> Hello Word</h1> <script type="module" > sayhello=()=>{ console.log('Hello'); } </script>

结果是: (index):14 Uncaught ReferenceError: sayhello is not defined at (index):14

您应该删除type=module

 <h1 onclick="sayhello()">Click</h1> <script > sayhello=()=>{ console.log('Hello'); } </script>

或者将函数附加到window以全局使用它:

 <h1 onclick="sayhello()">Click</h1> <script type="module"> window.sayhello=()=>{ console.log('Hello'); } </script>

你的脚本应该是这样的:

<script>
  function sayHello(){  
    console.log('hello')
  }
</script>

 <button onclick="hellosay()">Click</button> <script type="module"> window.hellosay=()=>{ console.log("hello") } </script>

对于 javascript 模块,创建一个 .js 或 .mjs 文件并导出你的 javascript 函数

我的模块.js

export function sayHell(){
    console.log("ok");
}

并导入它。

这里的示例https://github.com/mdn/js-examples/tree/master/modules/basic-modules

此处的文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM