【问题标题】:Save forms in localstorage将表单保存在本地存储中
【发布时间】:2019-06-27 20:04:43
【问题描述】:

所以,我在一个网站上工作,我需要保存一些它在表单中引入的数据。这个想法是保存该数据以供以后查询,就像表单的“存档”一样。没有php,没有服务器端,我需要全部在本地制作。有没有办法管理它?

谢谢

【问题讨论】:

  • 正是你所说的。 LocalStorage(或其变体之一)。到目前为止,您尝试了什么,什么对您不起作用?看看this jQuery plugin(它也管理不同的本地存储)。
  • 我想知道是否有办法以某种方式“自动”获取表单中引入的所有数据。如果没有,我只看到了一种方法:通过每个元素的 id 获取这些值,但这会花费很多时间......
  • 不,您不需要手动操作。只需使用 JSON.stringify 对表单进行字符串化,然后将其保存在本地(参见链接,您可以使用 LocalStorage、SessionStorage 或作为最终资源的 cookie)。
  • 我不太习惯使用 json,但我会检查一下。你说的Whick链接在哪里?谢谢;)
  • 我第一条评论中的链接! :) 我在这里重复:shaneriley.tumblr.com/post/1729353009/…

标签: html forms local-storage


【解决方案1】:

你可以试试这样的:

JS

//first check to see how many form records exist, if none set to 0 in storage
if (!localStorage.getItem('forms')) {
    localStorage.setItem('forms', 0);
}
else {
    forms = localStorage.getItem('forms');
}

//increment to the next form entry
forms++;

//save the form data to localStorage
localStorage.setItem('form.' + forms + '.firstName', document.getElementById('firstName'));

//lastly, save the number of forms to localStorage
localStorage.setItem('forms', forms);


HTML

<input type="text" id="firstName" />



这将在localStorage 中产生一条标记为form.1.firstName 的记录。输出只是对表单记录数量的另一个简单检查,并循环遍历迭代。

【讨论】:

    猜你喜欢
    • 2018-09-24
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2021-09-21
    • 2016-04-29
    • 2013-02-02
    相关资源
    最近更新 更多