简体   繁体   中英

Unable to retrieve dynamically generated content from localStorage

I have an HTML table with the id "roster1" that allows users to add table rows with a button click, and I am attempting to save the table state via a "Save" button that runs the following piece of code:

function saveRoster () {
        localStorage.setItem('rosterPd1','');
        var roster = document.getElementById ('roster1');
        localStorage.setItem('rosterPd1', roster);
        }

If I input some static value into 'rosterPd1', then I can use the information written to localStorage with no problem. However, when I attempt to save the table by using the above code, I get [object HTMLTableElement] returned... which is CORRECT, but not particularly useful!

Can someone point me in the right direction on what I would have to do to get localStorage to save the contents of the table itself?

You can only save Strings to Storage , but it seems for what you're trying to do, innerHTML will suffice;

function saveRoster() {
    var roster = document.getElementById('roster1');
    if (!roster) return; // not found
    localStorage.setItem('rosterPd1', roster.innerHTML); // store innerHTML
}
function loadRoster() {
    var roster = document.getElementById('roster1');
    if (!roster) return; // not found
    roster.innerHTML = localStorage.getItem('rosterPd1'); // get+apply innerHTML
}

As for why you're getting [object HTMLTableElement] , this is what happens when you call toString on a JavaScript reference to a <table> .

document.createElement('table').toString() // "[object HTMLTableElement]"

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