addEventListener 在被点击之前执行

addEventListener Executing Before Being Clicked

我正在开发一个以视频游戏为中心的基本 Chrome 扩展。为了创建菜单,我使用了 HTML 并提出:

    <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>

为了在单击按钮时接收输入,我使用了这个:

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")

(以上为Javascript) 唯一的问题是函数 startGame()openInfo() 在单击相应按钮之前正在执行。此代码取自关于内容安全策略的 chrome 页面(https://developer.chrome.com/extensions/contentSecurityPolicy) which states that this should work. I also attempted the solution on this post 但未能将其调整为我自己的代码。

不要像这里那样调用 startGameopenInfo 函数:

document.querySelector("#startButtonImage").addEventListener('click', startGame());
document.querySelector("#infoButtonImage").addEventListener('click', openInfo());

改为:

 document.querySelector("#startButtonImage").addEventListener('click', startGame);
 document.querySelector("#infoButtonImage").addEventListener('click', openInfo);

这会将函数本身作为参数传递给 addEventHandler 函数,而不是函数的 return 值。

你只需要传递引用,因为第二个参数是callback

document.querySelector("#startButtonImage").addEventListener('click', startGame);
document.querySelector("#infoButtonImage").addEventListener('click', openInfo);