【问题标题】:Button click event binding in Electron jsElectron js中的按钮单击事件绑定
【发布时间】:2017-08-23 10:55:09
【问题描述】:

我已经开始使用electron js开发桌面应用了。

我想知道如何将按钮点击事件与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!!!');
    }

但我收到以下错误:

未捕获的引用错误:未定义 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>

【问题讨论】:

  • 你在哪里设置getData函数?
  • @aug:更新了帖子。我在 renderer.js 中设置
  • 尝试将script 标记移到body 上方。现在的问题是在 DOM 呈现输入之后定义函数的脚本,因此如果它不存在,它自然不知道如何绑定 click 事件。
  • 我尝试在 head 部分移动脚本标签,仍然是同样的错误。

标签: node.js electron


【解决方案1】:

为将来的用户解释这一点。 HTML 文档中的&lt;script&gt; 标签在全局范围内执行,这意味着this === window,即脚本中声明的任何函数或变量都会固有地变为全局的。

当您 require 一个脚本时,它会在自己的上下文中被隔离(它被包装在另一个函数中,因此 this !== window,即脚本中声明的任何函数或变量都不能全局使用。

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

function getData() {
    ...
}

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

【讨论】:

  • electron中如何使用event参数?
猜你喜欢
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多