Tengo un proyecto para la escuela, que consiste en hacer un editor de texto. Agregué un botón de menú, que se supone que se debe hacer clic y deshabilitar después de hacer clic 2 veces, por lo que no agregará más y más elementos secundarios del botón de menú. Aquí está el código:
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);Como puede ver, tengo un botón que, después de hacer clic, agrega un nuevo botón al cuerpo del documento. Y si hace clic en él 2 o 3 veces, se agregan 3 botones nuevos, lo cual tiene errores. Intenté agregar un contador como este:
let counter = 0; if (counter === 2) { document.querySelector("button")[0].disabled = "disabled"; || document.querySelector("button")[0].disabled = true; }Bueno, eso no pareció funcionar como se esperaba. ¿Alguna idea sobre cómo hacer que esto funcione? Gracias
Debe inicializar el counter fuera del controlador de eventos onclick . Luego puede agregar este código al final del controlador de eventos 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);