如何在JavaScript中正确保存表单数据到localStorage,解决刷新丢失问题
解决表单数据持久化到localStorage并自动回填的问题
你的代码已经实现了点击按钮时将数据存入localStorage的逻辑,但缺少页面加载时从localStorage读取数据并回填到表单的步骤,所以刷新页面后表单会是空的。另外,表单标签的写法不符合规范(自闭合的<form ... />需要改为完整的闭合标签),虽然浏览器会容错,但建议修正。
以下是修正后的完整代码:
<!DOCTYPE html> <html> <head> <title>表单数据持久化</title> </head> <body> <form action="test.php" class="form1" method="post"> <input name="firstname" type="text" id="firstname" class='' placeholder="firstname"><br> <input name="lastname" type="text" id="lastname" class='' placeholder="lastname"><br> <button onclick="store()" type="button">Store Form Data</button> <!-- 可选:提交表单时自动保存数据 --> <button type="submit" onclick="store()">提交并保存</button> </form> <script type="text/javascript"> // 页面加载完成后自动回填存储的数据 document.addEventListener('DOMContentLoaded', function() { const storedFirstname = localStorage.getItem("firstname_data"); const storedLastname = localStorage.getItem("lastname_data"); if (storedFirstname) { document.getElementById('firstname').value = storedFirstname; } if (storedLastname) { document.getElementById('lastname').value = storedLastname; } }); function store(){ const firstname = document.getElementById('firstname').value; localStorage.setItem("firstname_data", firstname); const lastname = document.getElementById('lastname').value; localStorage.setItem("lastname_data", lastname); alert(`已保存:${firstname} ${lastname}`); } </script> </body> </html>
关键修正说明:
- 修复表单闭合方式:将
<form ... />改为<form ...>+</form>的完整结构,符合HTML规范。 - 新增页面加载逻辑:通过
DOMContentLoaded事件监听,在页面加载完成后自动读取localStorage中的数据,填充到对应输入框。 - 优化存储提示:合并alert提示,更简洁直观。
- 可选增强:给提交按钮绑定store函数,确保表单提交时也能同步保存数据。
验证方式:
- 输入内容后点击Store按钮,数据会存入localStorage。
- 刷新页面,输入框会自动填充之前保存的内容。
- 打开浏览器开发者工具(F12),在「Application」(或「存储」)面板的localStorage中,可查看
firstname_data和lastname_data的持久化数据。
内容的提问来源于stack exchange,提问作者Nancy Moore
相关产品推荐
相关产品推荐

