[英]How do i disable a button after i have clicked it 2 times?
我有一個學校項目,其中包括制作一個文本編輯器。 我添加了一個菜單按鈕,它應該在單擊2次后被單擊並禁用,所以它不會 append 越來越多的菜單按鈕的孩子。 這是代碼:
let btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Open Menu';
btn.onclick = () => {
let btn2 = document.createElement('input');
btn2.type = 'button';
btn2.value = 'New Text';
document.body.appendChild(btn2);
}
document.body.appendChild(btn);
如您所見,我有一個按鈕,單擊該按鈕后,會在文檔正文中附加一個新按鈕。 如果您單擊它 2 或 3 次,則會附加 3 個新按鈕,這是錯誤的。 我嘗試添加這樣的計數器:
let counter = 0;
if (counter === 2) {
document.querySelector("button")[0].disabled = "disabled"; || document.querySelector("button")[0].disabled = true;
}
好吧,這似乎並沒有按預期進行。 關於如何使它工作的任何想法? 謝謝
您應該在onclick
事件處理程序之外初始化counter
。 然后您可以在onclick
事件處理程序的末尾添加此代碼:
counter++;
if (counter === 2) btn.disabled = true;
const btn = document.createElement('input'); let counter = 0; btn.type = 'button'; btn.value = 'Open Menu'; btn.onclick = () => { let btn2 = document.createElement('input'); btn2.type = 'button'; btn2.value = 'New Text'; document.body.appendChild(btn2); counter++; if (counter === 2) btn.disabled = true; } document.body.appendChild(btn);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.