addEventListener在单击之前执行

人气:616 发布:2022-10-16 标签: javascript queryselector google-chrome-extension addeventlistener

问题描述

我正在开发围绕视频游戏的基本Chrome扩展程序.为了创建菜单,我使用了HTML并提出:

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

(以上为Javascript)唯一的问题是,在单击相应按钮之前,函数 startGame() openInfo()正在执行.这段代码取材自chromes页面,有关内容安全策略( https://developer.chrome.com/extensions/contentSecurityPolicy ),该代码应可以正常工作.我还尝试了这篇文章中的解决方案 addEventListener('click')是独立执行的,但无法将其调整为我自己的代码.

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

推荐答案

不要像在此处那样调用 startGame openInfo 函数:

Don't call the startGame and openInfo functions as you do here:

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 函数,而不是函数的返回值.

This passes the function itself as a parameter to the addEventHandler function, rather than the return value of the function.

799