node.js Electron js 中的按钮点击事件绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43102216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Button click event binding in Electron js
提问by Manprit Singh Sahota
I have started using electron js to develop desktop application.
我已经开始使用电子 js 来开发桌面应用程序。
I want to know that how to bind button click event with javascript function so that I can perform other operation.
我想知道如何用javascript函数绑定按钮点击事件,以便我可以执行其他操作。
I used below HTML code:
我使用了以下 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>
My renderer.js code looks like this:
我的 renderer.js 代码如下所示:
function getData(){
console.log('Called!!!');
}
But I am getting error that:
但我收到以下错误:
Uncaught ReferenceError: getData is not defined at HTMLInputElement.onclick
未捕获的 ReferenceError:getData 未在 HTMLInputElement.onclick 中定义
Am I doing something wrong?
难道我做错了什么?
Update
更新
Updated HTML document and removed require() method and its working now:
更新了 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>
回答by MarshallOfSound
To explain this for future users. <script>tag's in an HTML document are executed in the global scope, this means that this === window, I.e. any function or variable declared in the script inherently becomes global.
为未来的用户解释这一点。 <script>HTML 文档中的标签在全局范围内执行,这意味着this === window,即脚本中声明的任何函数或变量本质上都变成全局的。
When you requirea script it becomes isolated in it's own context (it is wrapped in another function so this !== window, I.e. any function or variable declared in the script is not available globally.
当你require编写一个脚本时,它在它自己的上下文中变得孤立(它被包装在另一个函数中this !== window,即脚本中声明的任何函数或变量都不是全局可用的。
The correct way to do this is to use require('./renderer.js')and to use this code
执行此操作的正确方法是使用require('./renderer.js')并使用此代码
function getData() {
...
}
document.querySelector('#btnEd').addEventListener('click', () => {
getData()
})

