简体   繁体   English

localStorage不存储前置注释

[英]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. 我试图通过将ul保存为varul存储前置注释,并在其上使用localStorage将其保存到浏览器中。

HTML: 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: 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 . val()显然旨在获取form元素 Trying it on a list returns an empty string. 在列表上尝试返回一个空字符串。 You could just get the innerhtml using $('#ul').html() , then stringifying that for localStorage . 您可以使用$('#ul').html()获得localStorage ,然后将其字符串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): 要在以后恢复它们(我在这里使用jQuery,因为仍然可以使用):

$('#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 . 在Chrome中,devtools位于“ Tools下的“ Chrome”菜单中,或者右键单击网页和“ Inspect element任意位置。

LocalStorage (and a bunch of other stuff) is listed in the Resources tab. Resources选项卡中列出了LocalStorage(以及其他一些东西)。 You can also go to the Console tab and type localStorage to access the object directly. 您也可以转到“ Console选项卡,然后键入localStorage以直接访问该对象。

Keep in mind localStorage only stores strings and is limited to 5MB per 'origin', which I take to mean host. 请记住,localStorage仅存储字符串,每个“源”限制为5MB,我指的是主机。 If you do lots of testing on localhost, I imagine there's a chance you'll hit the quota at some point. 如果您在localhost上进行了大量测试,我想您有机会在某个时候达到配额。

Also, the previous commenter has a good point about using getItem() / setItem() . 另外,以前的评论者对使用getItem() / setItem()有一个很好的了解。 Instead of using localStorage.comments you'd use localStorage.getItem('comments') . 而不是使用localStorage.comments而是使用localStorage.getItem('comments')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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