简体   繁体   中英

localStorage not storing prepended comments

Here is the fiddle. I am trying to store prepended comments in a ul by saving the ul as a var , and use localStorage on it to save it to the browser.

HTML:

<h1>Commentia!!!</h1>
<textarea id='type'></textarea>
<br />
<input type='text' id='input'>
<br />
<br />
<button id='b' onclick='comment()'>Submit</button>
<div id='box'>Type your comment
<br />(please use spaces)</div>
<div id='button'>Click to submit</div>
<div id='inp'>Type your name</div>
<div id='dialog'></div>
<h3>Comments</h3>
<ul id='ul'></ul>

JS:

var l = $('#ul').val();
localStorage.comments = l;
document.getElementById('ul').innerHTML = localStorage.comments;

val() is apparently meant for getting the values of form elements . Trying it on a list returns an empty string. You could just get the innerhtml using $('#ul').html() , then stringifying that for localStorage .

Something like:

var l = $('#ul').html();
localStorage.comments = JSON.stringify(l);

To restore these at some later point (I use jQuery here since that's available anyway):

$('#ul').html(JSON.parse(localStorage.comments));

(Untested). Any particular reason for taking this approach?

Edit: it's easy enough to check what is actually being saved. In Chrome, the devtools are in the Chrome menu under Tools , or right-click anywhere in a webpage and Inspect element .

LocalStorage (and a bunch of other stuff) is listed in the Resources tab. You can also go to the Console tab and type localStorage to access the object directly.

Keep in mind localStorage only stores strings and is limited to 5MB per 'origin', which I take to mean host. If you do lots of testing on localhost, I imagine there's a chance you'll hit the quota at some point.

Also, the previous commenter has a good point about using getItem() / setItem() . Instead of using localStorage.comments you'd use localStorage.getItem('comments') .

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