简体   繁体   中英

How to store created elements in Cookies or localStorage using javascript?

I dynamically create some a tags with JavaScript when clicking on other elements. When I refresh the page, the created elements disappear. Is there a way to store the creation of the elements in a JavaScript cookie?

function showTab(ev) {
    let head = document.getElementById('heading');
    let node = document.createElement("a"); 
    node.classList.add("tab");
    node.appendChild(document.createTextNode(ev.target.innerHTML));
    head.appendChild(node); 
};

Cookies are probably not the right way to go about something like this as there are size limitations

A better approach would be to store added elements inside the browser's localStorage or indexedDB . You can see an example of the latter in this simple todo app: http://todomvc.com/examples/react/#/

If you inspect the localStorage on that todo example after adding some items, you will see that there is an array containing your entries in JSON format.

Depending on what type of information you need to save, you could either save the HTML directly, or you could save JSON containing the relevant information (tab name, link URL, etc).

I would recommend against saving the HTML directly in case you ever need to make changes to the HTML on your site. Your users would then be loading up outdated HTML.

You can store outerHTML of created element in localStorage and get it on page load

var node = document.createElement("a");
node.classList.add("tab");
node.textContent = "new tag";     

var local = localStorage.getItem("html");
if (local == null){
  localStorage.setItem("html", node.outerHTML);
  console.log('HTML setted in localStorage');
} else
    console.log(local);

Because localStorage doesn't worked in snippet you should check it in jsfiddle

Note that if your html content is large you should consider max size of local storage

Okay, I solved it like that:

// Restore

window.onload = function() {
let head = document.getElementById('heading');
archive = [];
key = allStorage();

for(var i=0; i<archive.length; i++){ 
    if(archive[i] != null){
        let node = document.createElement("a");
        node.classList.add("tab");
        node.innerHTML = key[i];

        head.appendChild(node);
    }
}
}


//Store all

function allStorage() {
keys = Object.keys(localStorage);           // Gibt alle Schlüssel zurück
archive = [];

for (var i=0; i< keys.length; i++) {
    archive.push(keys[i]);
}
return archive;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM