button点击事件绑定在电子JS

我已经开始使用电子js来开发桌面应用程序。

我想知道如何绑定button点击事件与JavaScript函数,以便我可以执行其他操作。

我使用下面的HTML代码:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Manav Finance</title> </head> <body> <input type="button" onclick="getData()" value="Get Data" /> </body> <script> // You can also require other files to run in this process require('./renderer.js') </script> </html> 

我的renderer.js代码如下所示:

 function getData(){ console.log('Called!!!'); } 

但是我得到的错误是:

Uncaught ReferenceError:getData未在HTMLInputElement.onclick处定义

难道我做错了什么?

更新

更新了HTML文档,并删除了require()方法及其工作:

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Manav Finance</title> <script src="renderer.js"></script> </head> <body> <input type="button" id="btnEd" value="Get Data" onclick="getData()" /> </body> </html> 

为未来的用户解释这一点。 HTML文档中的<script>标签在全局范围内执行,这意味着this === window ,即在脚本中声明的任何函数或variables本质上变成全局的。

当你require一个脚本时,它会在它自己的上下文中被隔离(它被包装在另一个函数中,所以this !== window ,即脚本中声明的任何函数或variables在全局上是不可用的。

正确的方法是使用require('./renderer.js')并使用此代码

 function getData() { ... } document.querySelector('#btnEd').addEventListener('click', getData)