Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
¿Cómo alternar dos elementos correctamente con dos botones?

Quiero mostrar las tarjetas cuando se hace clic en las tarjetas y mostrar la tabla cuando se hace clic en la tabla. Pero por defecto, uno de ellos debe mostrarse al principio con el otro oculto. Pero si se vuelve a hacer clic en cualquiera de los botones, el div permanecerá en lo que se hizo clic. Lo tengo a medias funcionando. Si comienza primero en el botón de la mesa, verá que funciona hasta que vuelva a hacer clic (el mismo botón) o comience en el botón de las cartas. Cualquier ayuda es apreciada. Aquí hay un ejemplo de lo que necesito.

 const targetTable = document.getElementById("table"); const targetCards = document.getElementById("cards"); const btn = document.getElementById("toggle"); const btn2 = document.getElementById("toggle2"); targetCards.style.display = "block"; targetTable.style.display = "none"; btn.onclick = function () { if (targetTable.style.display !== "none") { targetTable.style.display = "none"; } else { targetTable.style.display = "block"; targetCards.style.display = "none"; } }; btn2.onclick = function () { if (targetCards.style.display !== "none") { targetCards.style.display = "none"; } else { targetCards.style.display = "block"; targetTable.style.display = "none"; } };
 <body> <div id="cards">This div shows cards.</div> <div id="table">This div shows table.</div> <button id="toggle">table</button> <button id="toggle2">cards</button> </body>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Aquí hay una forma de abordarlo. Use clases para consolidar sus funciones, luego use un atributo de datos para designar qué botón revela qué elemento

 document.querySelectorAll('.toggler').forEach(button => { button.addEventListener('click', e => { let targ = `#${e.target.dataset.ref}`; // set them all to hidden document.querySelectorAll('.toggles').forEach(div => div.classList.add('hide')); // reveal the one we want document.querySelector(targ).classList.remove('hide'); }); });
 .hide { display: none; }
 <div id="cards" class='toggles'>This div shows cards.</div> <div id="table" class='toggles hide'>This div shows table.</div> <button class='toggler' data-ref='table'>table</button> <button class='toggler' data-ref='cards'>cards</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Un poco tarde, pero me gustan las tareas js :-)

 const btns = document.querySelectorAll('.toggle'); const elem = document.querySelectorAll('.elem'); btns.forEach((b) => { b.addEventListener('click', (e) => { const t = e.target.getAttribute('data-type'); const classList = document.getElementById(t).classList; if (classList.length > 1) { elem.forEach((c) => { c.classList.toggle('hidden') }) } }); });
 .hidden { display: none; }
 <div> <div id="cards" class="elem ">This div shows cards.</div> <div id="table" class="elem hidden">This div shows table.</div> <button class="toggle" data-type="table">table</button> <button class="toggle" data-type="cards">cards</button> </div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Si entiendo su pregunta correctamente, la ha complicado demasiado con las declaraciones if. Es necesario verificar cuáles son los estados actuales, simplemente puede configurarlos para lo que se supone que deben hacer los botones.
Las funciones pueden verse así:

 btn.onclick = function () { targetCards.style.display = "none"; targetTable.style.display = "block"; }; btn2.onclick = function () { targetTable.style.display = "none"; targetCards.style.display = "block"; };

Y aquí está todo el fragmento de trabajo:

 const targetTable = document.getElementById("table"); const targetCards = document.getElementById("cards"); const btn = document.getElementById("toggle"); const btn2 = document.getElementById("toggle2"); targetCards.style.display = "block"; targetTable.style.display = "none"; btn.onclick = function () { targetCards.style.display = "none"; targetTable.style.display = "block"; }; btn2.onclick = function () { targetTable.style.display = "none"; targetCards.style.display = "block"; };
 <body> <div id="cards">This div shows cards.</div> <div id="table">This div shows table.</div> <button id="toggle">table</button> <button id="toggle2">cards</button> </body>

También puede ser un poco elegante si tiene un botón que alterna la pantalla. No es mucho más complicado.

 const targetTable = document.getElementById("table"); const targetCards = document.getElementById("cards"); const btn = document.getElementById("toggle"); targetCards.style.display = "block"; targetTable.style.display = "none"; btn.onclick = function () { if (targetTable.style.display !== "none") { targetTable.style.display = "none"; targetCards.style.display = "block"; btn.innerHTML = "table"; } else { targetTable.style.display = "block"; targetCards.style.display = "none"; btn.innerHTML = "cards"; } };
 <body> <div id="cards">This div shows cards.</div> <div id="table">This div shows table.</div> <button id="toggle">table</button> </body>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda