首页 > 解决方案 > 点击时添加事件监听器

问题描述

我有一个按钮定义如下

index.html

<body>
  <section>
    <button id="open-file">Open File</button>
    ...(series of other similar buttons)...

  </section>
</body>

<script>
    require('./renderer');
</script>

renderer.js

const openFileButton = document.querySelector('#open-file');
...

openFileButton.addEventListener('click', () => {
  console.log('You clicked the "Open File" button.');
});

main.js

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    show: false,
    webPreferences: {
        nodeIntegration: true
    }
  });
  mainWindow.loadFile('app/index.html');
  ...
});

当我在应用程序窗口中单击该按钮时,控制台中没有任何反应。我需要添加任何额外的步骤来执行此事件侦听器吗?

标签: javascriptnode.jselectron

解决方案


你试过<script src="./renderer.js"></script>吗?你确定你的renderer.js运行符合预期吗?

只是为了澄清,require()在客户端 JavaScript 中不存在。打开你的浏览器开发者控制台,你应该会看到它require()没有被定义。

查看MDN 脚本标签文档,了解如何包含 .js 文件的更多信息。


推荐阅读