简体   繁体   English

单击按钮时如何从HTML调用导出的函数?

[英]how call exported function from HTML when button is clicked?

simple webpack setup. 简单的webpack设置。 index.html and index.js files. index.html和index.js文件。 In HTML is button onclick="ok_click()". 在HTML中是按钮onclick =“ ok_click()”。 Why can I not call the ok_click function that is defined in the index.js file? 为什么我不能调用index.js文件中定义的ok_click函数? I get function not found error. 我得到函数未找到错误。

I tried to export the ok_click function from index.js. 我试图从index.js导出ok_click函数。 Then in index.html, inside script tag, import from index.js. 然后在index.html中的脚本标签中,从index.js导入。 Get error saying the import statement is not recognized. 收到错误消息,指出无法识别导入语句。

in index.html 在index.html中

  <button onclick="ok_click( )">ok</button>

in index.js 在index.js中

function ok_click( )
{
  console.log('in ok_click') ;
}
export { ok_click } ;

I think webpack usually apply the scripts at the end of the HTML file. 我认为webpack通常在HTML文件的末尾应用脚本。 This would mean that when the button onclick is bound there is in fact no javascript available yet. 这意味着绑定onclick按钮时,实际上还没有可用的javascript。 Have you tried looking at what the generated files look like? 您是否尝试查看生成的文件的外观? And remember to make sure the window is loaded. 并请记住确保已加载窗口。

Try a different approach like: 尝试不同的方法,例如:

Index.js: Index.js:

function init() {
 var btn = document.getElementById("btn");
     btn.addEventListener("click", () => {
       console.log("in ok_click");
      });
}
window.onload = init;

Index.html 的index.html

<button id="btn">ok</button>

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

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