繁体   English   中英

单击按钮时只运行一次 function? Javascript

[英]Run function only once when button is clicked? Javascript

我想要 function home(); 只执行一次。 当玩家选择他们的武器时,每次点击三个按钮之一时,它都会创建一个主页按钮。 它怎么能运行一次,所以无论再次玩游戏多少次,都只创建一个主页按钮? 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);

添加检查是否已运行。 一个简单的boolean

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

其他选项是检查元素是否存在

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

我认为你需要这个:

 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>

由于您的home()函数添加了<button id='homebutton'> ,因此您可以使用 JS 检查该 ID 是否已存在于 DOM 中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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