html5 localStorage实现表单本地存储

2023-08-09,

随笔开头,我不得不吐槽,为什么我的随笔每次发布之后,都会在分分钟之内移出首页.好气啊!!

进入正题了,项目中有许多表单输入框要填写,还有一些单选复选框之类的.用户可能在填写了大量的信息之后,不小心刷新了页面或者出现了什么异常,导致页面上填写的信息消失了.还得重新填写信息,麻烦至极.

html5推出了本地存储的功能,localStorage以及sessionStorage.我打算利用他们来实现一个临时存储的功能,即使页面刷新,数据依然保留.

1.页面初始如下:

 2.代码如下

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面刷新后保留表单的值</title>
<style>
#savehistory{
width: 400px;margin: 0 auto;
}
.userselect{
-moz-user-select: none;
-webkit-user-select: none;
}
</style>
</head>
<body>
<div id="savehistory">
<div class="userselect">hhhhhhhhhh</div>
<input class="userselect" type="text"><br/>
<input type="text"><br/>
<input type="text"><br/>
<input type="text"><br/>
<input type="text"><br/>
<input type="button" value="按钮1"><br/>
<input type="button" value="按钮2"><br/>
<input type="radio" name="sex"><br/>
<input type="radio" name="sex"><br/>
<input type="checkbox"><br/>
<input type="checkbox"><br/>
<input type="checkbox"><br/>
<button id="save">一键缓存</button>
</div>
</body>
<script src="jquery-1.7.2.min.js"></script>
<script>
$(function () {
var localMsg;
if(window.localStorage.formHistory){
localMsg=JSON.parse(window.localStorage.formHistory);
}
if(localMsg && localMsg.length>=1){
var realIndex=0;
for(var i=0;i<$('#savehistory input').length;i++){
if($($('#savehistory input')[i])[0].type=='text'){
$($('#savehistory input')[i]).val(localMsg[realIndex].text)
realIndex++;
}else if($($('#savehistory input')[i])[0].type=='radio'){
$($('#savehistory input')[i]).prop('checked',localMsg[realIndex].radio)
realIndex++;
}else if($($('#savehistory input')[i])[0].type=='checkbox'){
$($('#savehistory input')[i]).prop('checked',localMsg[realIndex].checkbox)
realIndex++;
}
}
}
$('#save').click(function () {
var history=[];
window.localStorage.formHistory='';
for(var i=0;i<$('#savehistory input').length;i++){
if($($('#savehistory input')[i])[0].type=='text'){
history.push({"text":$($('#savehistory input')[i]).val()})
}else if($($('#savehistory input')[i])[0].type=='radio'){
history.push({"radio":$($('#savehistory input')[i]).attr('checked') ? 'checked' :''})
}else if($($('#savehistory input')[i])[0].type=='checkbox'){
history.push({"checkbox":$($('#savehistory input')[i]).attr('checked') ? 'checked' :''})
}
}
window.localStorage.formHistory=JSON.stringify(history)
})
})
</script>
</html>

  3.在表单中填写好信息,并点击一键缓存

    4.将表单信息存储在localStorage中:

 5.f5刷新之后,js代码会去遍历localStorage.formHistory,然后取出来放在对应的位置.赶快来试一试吧!

html5 localStorage实现表单本地存储的相关教程结束。

《html5 localStorage实现表单本地存储.doc》

下载本文的Word格式文档,以方便收藏与打印。