Estoy planeando aumentar la cantidad de elementos en el div "fuente" de dos a tres. Pero para aumentarlo, necesito crear muchas líneas de código nuevas con prácticamente los mismos datos (const tres, nueva función appendIt2 y agregar un extra si está en la ventana. onload).
Tal vez pueda aconsejarme cómo puedo reducir el desorden en este script y hacer que sea más fácil de editar y leer.
const one = document.getElementById("element"); element.addEventListener("click", appendIt); function appendIt() { localStorage.setItem("append", "true"); var element = document.getElementById("element"); document.getElementById("destination").appendChild(element); } const two = document.getElementById("element1"); element1.addEventListener("click", appendIt1); function appendIt1() { localStorage.setItem("append1", "true"); var element1 = document.getElementById("element1"); document.getElementById("destination").appendChild(element1); } window.onload = () => { if (localStorage.getItem("append") == "true") { appendIt(); } if (localStorage.getItem("append1") == "true") { appendIt1(); } }; function clearstorage() { localStorage.clear(); location.reload(); } #destination { display: flex; flex-direction: column; background-color: red; } #source { display: flex; flex-direction: column; background-color: beige; } <button onclick="clearstorage()"> Reset order </button> <div id="destination"></div> <div id="source"> <a id="element" href="#">One</a> <a id="element1" href="#">Two</a></div>Primero, cree una función genérica para agregar
function append(itemName, elementId) { localStorage.setItem(itemName, "true"); let element = document.getElementById(elementId); document.getElementById("destination").appendChild(element1); }Para usarlo, pase una función de flecha como devolución de llamada al detector de eventos, de esta manera:
theElement.addEventListener("click", () => append("append", "element"));Esto conduciría a:
function append(itemName, elementId) { localStorage.setItem(itemName, "true"); let element = document.getElementById(elementId); document.getElementById("destination").appendChild(element1); } const one = document.getElementById("element"); // Use arrow function as callback to pass the proper values to the generic append() function // I replaced 'element' variable with 'one' here, which is the element you just retrieved one.addEventListener("click", () => append("append", "element")); const two = document.getElementById("element1"); two.addEventListener("click", () => append("append1", "element1")); // When appending new child: // const three = document.getElementById("element2"); // three.addEventListener("click", () => append("append2", "element2")); window.onload = () => { if (localStorage.getItem("append") == "true") { append("append", "element"); } if (localStorage.getItem("append1") == "true") { append("append1", "element1") } }; function clearstorage() { localStorage.clear(); location.reload(); } #destination { display: flex; flex-direction: column; background-color: red; } #source { display: flex; flex-direction: column; background-color: beige; } <button onclick="clearstorage()"> Reset order </button> <div id="destination"></div> <div id="source"> <a id="element" href="#">One</a> <a id="element1" href="#">Two</a></div>Si quieres ir más allá, podrías tener un mapa como:
const appendToElementMap = { "element": "append", "element1": "append1" };e iterar sobre sus entradas para agregar los detectores de eventos
Sugeriría mantener sus funciones en un archivo javascript separado en alguna carpeta de utilidad. Esa carpeta debe contener archivos que tengan algún propósito significativo. Y mejore su convención de nomenclatura también, tal vez eso facilitará un poco el proceso. Te ayudará a largo plazo.