简体   繁体   中英

Cannot react to click event in Electron app

I have packaged my HTML+CSS+JS app into an executable using Electron, however it doesn't work the same way as it does in a browser. Specifically, my app doesn't seem to react to click events, whereas if I run the app in a browser, the click event gets caught no problem.

Here's how I structured my app. In a file called index.html I have the following:

<!DOCTYPE html>
<html>
<head>
   ...
    <script src="js/default.js"></script>
   ...
</head>
<body onload="prepareGame()">
    ...
</body>
</html>

The function prepareGame() , which is defined inside js/default.js , is where I add a click listener to an element of the DOM:

function prepareGame() {
    ...
    gameArea.addEventListener('click', clickListener);
}

where clickListener is also defined in js/default.js and is the function that I want to execute upon a click event. The problem is that clickListener does not get executed when I click on the element for which I registered a listener. Even more strange is the fact that prepareGame() does get executed (I've checked that by putting an alert() inside of it), and so does the line gameArea.addEventListener('click', clickListener); , however clickListener() doesn't get called when I click on the element. Notice that I don't have this problem when I run my app on a browser, ie clickListener() gets executed when I click on the element.

I honestly don't understand why this is happening.

Maybe try it like this using script and not events in the HTML.

I don't know how you initialise the gameArea object, but here we get it when the DOM is ready.

 let gameArea; const clickListener = ({ target }) => { console.log(target.innerHTML); }; const prepareGame = () => { // set gameArea now DOM is ready gameArea = document.querySelector('.gameArea'); gameArea.addEventListener('click', clickListener); } document.addEventListener('DOMContentLoaded', () => { prepareGame(); });
 <!DOCTYPE html> <html> <head> </head> <body class="gameArea"> <div>1</div> <div>2</div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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