问题
I'm Developing a basic Chrome extension centred around a video game. In order to create the menu I have used HTML and come up with:
<head>
<title>Inheritance Popup</title>
<script src="popup.js"></script>
</head>
<body style="background-color:#4d2b88">
<img
src= "start_screen.png"
id='startScreenImage'
style="z-index: -1;">
<img
src= "start_button.png"
id='startButtonImage'
style="position:absolute; left:65px; top:145px;">
<img
src= "info_button.png"
id='infoButtonImage'
style="position:absolute; left:65px; top:295px;">
</body>
</html>
In order to receive input upon the buttons being clicked I am using this:
function startGame(){
console.log("start works")
}
// Add event listeners once the DOM has fully loaded by listening for the
// `DOMContentLoaded` event on the document, and adding your listeners to
// specific elements when it triggers.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector("#startButtonImage").addEventListener('click', startGame());
document.querySelector("#infoButtonImage").addEventListener('click', openInfo());
});
function openInfo(){
console.log("info works")
(The above is Javascript)
The only issue is that the functions startGame()
and openInfo()
are executing before the corresponding buttons are clicked. This code was taken from chromes page about content security policy (https://developer.chrome.com/extensions/contentSecurityPolicy) which states that this should work. I also attempted the solution on this post addEventListener('click') is executing on its own but was unsuccessful in adjusting it to my own code.
回答1:
Don't call the startGame
and openInfo
functions as you do here:
document.querySelector("#startButtonImage").addEventListener('click', startGame());
document.querySelector("#infoButtonImage").addEventListener('click', openInfo());
Instead do:
document.querySelector("#startButtonImage").addEventListener('click', startGame);
document.querySelector("#infoButtonImage").addEventListener('click', openInfo);
This passes the function itself as a parameter to the addEventHandler
function, rather than the return value of the function.
回答2:
You only need to pass the reference, as second parameter is a callback
document.querySelector("#startButtonImage").addEventListener('click', startGame);
document.querySelector("#infoButtonImage").addEventListener('click', openInfo);
来源:https://stackoverflow.com/questions/63534418/addeventlistener-executing-before-being-clicked