隨筆開頭,我不得不吐槽,爲何個人隨筆每次發佈以後,都會在分分鐘以內移出首頁.好氣啊!!javascript
進入正題了,項目中有許多表單輸入框要填寫,還有一些單選複選框之類的.用戶可能在填寫了大量的信息以後,不當心刷新了頁面或者出現了什麼異常,致使頁面上填寫的信息消失了.還得從新填寫信息,麻煩至極.html
html5推出了本地存儲的功能,localStorage以及sessionStorage.我打算利用他們來實現一個臨時存儲的功能,即便頁面刷新,數據依然保留.html5
1.頁面初始以下:java
2.代碼以下jquery
<!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.在表單中填寫好信息,並點擊一鍵緩存web
4.將表單信息存儲在localStorage中:緩存
5.f5刷新以後,js代碼會去遍歷localStorage.formHistory,而後取出來放在對應的位置.趕快來試一試吧!session