Me gustaría cambiar el contenido de un div. Tengo tres divs:
<div class="box1" style="height: 200px; width: 200px; background-color: red" > A </div> <br /> <div class="box2" style="height: 200px; width: 200px; background-color: blue" > <label for="">tex</label> <input type="text" /> </div> <br /> <div class="box3" style="height: 200px; width: 200px; background-color: yellow" > C </div>cuando la página está lista, las casillas 2 y 3 muestran ninguno:
function hideElementBoxOnLoad() { let box1 = document.querySelector(".box1"); let box2 = document.querySelector(".box2"); let box3 = document.querySelector(".box3"); box2.style.display = "none"; box3.style.display = "none"; } $(document).ready(hideElementBoxOnLoad);Quiero un clic que cambie el contenido de box2 y box3 a box1 y luego vuelva al contenido de box1:
function changeContent() { let chang = true; let box1 = document.querySelector(".box1"); let box2 = document.querySelector(".box2"); let box3 = document.querySelector(".box3"); let box2Content = box2.textContent; let box3Content = box3.textContent; if (chang) { box1.textContent = box2Content; chang = !chang; if ((box1.textContent === box2Content)) { box1.textContent = box3Content; } } } let btn = document.getElementById("btn"); btn.addEventListener("click", changeContent);Hasta ahora funcionó pero no muestra el contenido de box2 solo box3. ¿Qué hice mal y qué mejor manera puedo alternar con un booleano?
Vea abajo
En lugar de intentar intercambiar contenido entre cada div, simplemente use JS para revisar la matriz de ellos e intercambiar una clase activa entre ellos;
var boxes = document.getElementsByClassName('box'); var change = document.getElementById('change'); var counter = 0; change.addEventListener('click', function(){ boxes[counter].classList.remove('active'); boxes[counter].nextElementSibling.classList.add('active'); counter++; if(counter === boxes.length) { counter = 0; boxes[0].classList.add('active'); } }); .box { display: none; width: 100px; height: 100px; background-color: gray; } .box.active { display:block } <div class="box active">A</div> <div class="box">B</div> <div class="box">C</div> <button id="change">Change Content</button>No estoy completamente seguro de haber entendido tu pregunta. pero debajo puedes ver e incluso probar con el botón de fragmento.
el botón ahora agrega cualquier contenido en el cuadro amarillo, y lo que está en el campo de entrada del cuadro azul en el cuadro rojo. enumerarlos hacia abajo.
si desea reemplazar el contenido por completo.
simplemente cambie la lógica a box1.innerHTML += spacer+box3.innerHTML+spacer+input.value
Esta es la forma más sencilla de hacerlo, es fácil de entender con solo leer el código, creo.
¡espero que esto ayude!
function changeContent() { //the button const btn = document.getElementById("btn"); //the boxes const box1 = document.getElementById("box1"); const box2 = document.getElementById("box2"); const box3 = document.getElementById("box3"); //a spacer const spacer = "<br>"; //the input field const input = document.getElementById("input"); //logic box1.innerHTML += spacer+box3.innerHTML+spacer+input.value } div{ border-radius: 5px; text-align: center; font-family: sans-serif; } #box1{ min-height: 200px; width: 200px; padding: 5px; background-color: rgb(255, 73, 73); } #box2 { height: 200px; width: 200px; padding: 5px; background-color: rgb(0, 195, 255); } #box3 { height: 200px; width: 200px; padding: 5px; background-color: yellow; } button{ padding: 3px; margin-top: 10px; } <div id="box1"> <p>contetnt A</p> </div> <br /> <div id="box2" > <label for="">tex</label> <input id="input" type="text" /> <button id="btn" onclick="changeContent()">click me</button> </div> <br /> <div id="box3"> contetnt C </div>Lista de errores: -
chang localmente en lugar de globalmente, lo que hace que sea cierto cada vez que ejecuta la función.Por ejemplo: - Cuando hace clic en el botón por primera vez, los datos se intercambian, pero para el segundo clic, los datos del primer div se pierden y no se pueden recuperar...
Solución : almacene los datos en una matriz en el controlador de eventos document.ready y extraiga los datos de la matriz para actualizar sus etiquetas html.
function hideElementBoxOnLoad() { let box1 = document.querySelector(".box1"); let box2 = document.querySelector(".box2"); let box3 = document.querySelector(".box3"); box2.style.display = "none"; box3.style.display = "none"; content = [box1.textContent, box2.textContent, box3.textContent]; let btn = document.getElementById("btn"); btn.addEventListener("click", changeContent); } var content = []; window.onload = (hideElementBoxOnLoad); var index = 0; function changeContent() { let chang = true; let box1 = document.querySelector(".box1"); /* let box2 = document.querySelector(".box2"); let box3 = document.querySelector(".box3"); let box2Content = box2.textContent; let box3Content = box3.textContent; if (chang) { box1.textContent = box2Content; chang = !chang; if ((box1.textContent === box2Content)) { box1.textContent = box3Content; } } */ function cycle(n, x = 0, y = content.length - 1, a = 1) { n += a; if (n > y) return x; if (n < x) return y; return n; } index = cycle(index); box1.textContent = content[index]; } <div class="box1" style="height: 200px; width: 200px; background-color: red"> A </div> <br /> <div class="box2" style="height: 200px; width: 200px; background-color: blue"> <label for="">tex</label> <input type="text" /> </div> <br /> <div class="box3" style="height: 200px; width: 200px; background-color: yellow"> C </div> <button id="btn"> CLICK ME </button>Explicación
Aquí primero almacené las etiquetas textContent en un content de matriz, al comienzo del código.
Luego, dentro del controlador de clic de botón, una función de cycle simple para recorrer los valores almacenados dentro de la matriz de content .