简体   繁体   English

单击时添加事件监听器

[英]addEventListener on click

I have a button defined as following我有一个按钮定义如下

In index.html :index.html

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

  </section>
</body>

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

In renderer.js :renderer.js中:

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

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

In main.js :main.js

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

When I click on that button in the app window, nothing happens in the console.当我在应用程序 window 中单击该按钮时,控制台中没有任何反应。 Are there any extra steps I need to add to execute this event listener?是否需要添加任何额外的步骤来执行此事件侦听器?

Have you tried <script src="./renderer.js"></script> ?你试过<script src="./renderer.js"></script>吗? Are you sure your renderer.js runs as intended?您确定您的renderer.js按预期运行吗?

Just to clarify, require() doesn't exist in client-side JavaScript. Open your browsers developer console and you should see that require() isn't defined.澄清一下,客户端 JavaScript 中不存在require() 。打开浏览器开发人员控制台,您应该会看到require()未定义。

Take a look at MDN script tag documentation for more information how you can include your.js files.查看MDN 脚本标签文档,了解有关如何包含 .js 文件的更多信息。

In your HTML file, you're using require in your script tag which is a Node.js specific function. Based on what you're expecting, it looks like you would like to link renderer.js to your HTML file.在您的 HTML 文件中,您在脚本标记中使用了require ,它是 Node.js 特定的 function。根据您的预期,您似乎希望将 renderer.js 链接到您的 HTML 文件。 Therefore, link it directly by entering <script src="renderer.js"></script> .因此,通过输入<script src="renderer.js"></script>直接链接它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM