简体   繁体   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>

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.

相关问题 如何使用onclick HTML属性调用JavaScript中的函数? - How can I use an onclick HTML attribute to call a function in JavaScript? 当模块已被 Z424516CA53B4AD4BEFZ37ED0 捆绑时,如何从 HTML 的模块中调用 javascript function? - How can I call a javascript function in a module from HTML when the module has been bundled by webpack? 如何在html中调用元素的onClick事件并等待单击发生。来自javascript中的另一个函数 - how can I call an onClick event of an element in html and wait until the click occurs.From another function in javascript 我如何从 HTML 文件中调用我的 Javascript function - How I can call my Javascript function from HTML file 如何从html文件中调用javascript函数 - How can I call a javascript function from an html file 如何从javascript onclick()事件中调用php函数? - How do I call a php function from javascript onclick() event? 如何从JavaScript调用LinkBut​​ton OnClick事件? - How can I call LinkButton OnClick Event from JavaScript? 如何从HTML中的onclick调用ASP函数? - How to call a ASP function from onclick in the HTML? 从 HTML 中的 JavaScript 模块调用 function - Call function from JavaScript module in HTML 从html onclick事件调用javascript文件中的函数 - Call function in javascript file from html onclick event
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM