[英]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>
result is: (index):14 Uncaught ReferenceError: sayhello is not defined at (index):14
结果是:
(index):14 Uncaught ReferenceError: sayhello is not defined at (index):14
You should either remove type=module
:您应该删除
type=module
:
<h1 onclick="sayhello()">Click</h1> <script > sayhello=()=>{ console.log('Hello'); } </script>
Or attach the function to window
to use it globally:或者将函数附加到
window
以全局使用它:
<h1 onclick="sayhello()">Click</h1> <script type="module"> window.sayhello=()=>{ console.log('Hello'); } </script>
This is what your script should look like:你的脚本应该是这样的:
<script>
function sayHello(){
console.log('hello')
}
</script>
<button onclick="hellosay()">Click</button> <script type="module"> window.hellosay=()=>{ console.log("hello") } </script>
For javascript modules create a .js or .mjs file and export your javascript functions对于 javascript 模块,创建一个 .js 或 .mjs 文件并导出你的 javascript 函数
Mymodule.js我的模块.js
export function sayHell(){
console.log("ok");
}
and import it.并导入它。
Samples here https://github.com/mdn/js-examples/tree/master/modules/basic-modules这里的示例https://github.com/mdn/js-examples/tree/master/modules/basic-modules
Documentation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules此处的文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.