Electron js中的按钮单击事件绑定 [英] Button click event binding in Electron js

查看:2282
本文介绍了Electron js中的按钮单击事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have started using electron js to develop desktop application.

我想知道如何将按钮单击事件与javascript函数绑定在一起,以便执行其他操作

I want to know that how to bind button click event with javascript function so that I can perform other operation.

我在HTML代码下面使用:

I used below HTML code:

<!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代码如下:

My renderer.js code looks like this:

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

但我收到以下错误消息:

But I am getting error that:


未捕获的ReferenceError:在HTMLInputElement.onclick上未定义getData

Uncaught ReferenceError: getData is not defined at HTMLInputElement.onclick

我做错什么了吗?

更新

已更新HTML文档并删除了require()方法及其现在可以正常工作:

Updated HTML document and removed require() method and its working now:

<!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 ,即

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.

当您要求一个脚本时,该脚本或脚本中的所有功能或变量都会固有地变为全局变量。自己的上下文(它包装在另一个函数中,所以 this!== window ,即脚本中声明的任何函数或变量都不全局可用。

When you require a 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('./ renderer.js')并使用此代码

The correct way to do this is to use require('./renderer.js') and to use this code

function getData() {
    ...
}

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

这篇关于Electron js中的按钮单击事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆