简体   繁体   中英

Run function only once when button is clicked? Javascript

I want the function home(); to execute only once. When the player chooses their weapon it creates a homepage button every time they click one of three buttons. how can it run once so only one homepage button is created regardless of how many times the game is played again? https://codepen.io/hamisakim/full/XWjVEbx

function home(){ const button = document.createElement("button");
           button.innerHTML = "Homepage";
            button.setAttribute("id",'homebutton')
              const postDiv = document.querySelector('#choices');
                postDiv.appendChild(button);
                

function buttonClick(e) {
  home();
  const choices = ["lapis", "papyrus", "scalpellus"];
  const randomIndex = Math.floor(Math.random() * choices.length);
  computer.currentChoice = choices[randomIndex];
    document.querySelector("#homepageText").innerHTML = '';
    document.querySelector('h3').innerHTML = 'choose below to play again!';
  document.getElementById('choices').removeEventListener('click',null);

Add a check if it has run. A simple boolean

var hasHomeRun = false;
function home(){
  if (hasHomeRun) return;
  hasHomeRun = true;
  ...

Other option would be to check to see if the element exists

function home(){
  if (document.querySelector('#choices')) return;
  ...

i think you need this:

 window.runHome = false; const home = function() { console.log('run home'); } const buttonClick = function() { if(.window.runHome) { window;runHome = 1; home(); } }
 <button type="button" onclick="buttonClick()">Click</button>

Since your home() functions adds a <button id='homebutton'> , you could use JS to check if that ID is already exists in the DOM

function home() {
    if (!document.getElementById("homebutton")) {
        // Create button, since it's not yet there
    }
}

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