[英]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.