在html 5中,localstorage是个不错的东西,在支持localstorage的浏览器中, 能持久化用户表单的输入,即使关掉浏览器,下次重新打开浏览器访问,也能读出其值, 下面给出的例子是使用jquery 在每次表单加载的时候,读localstorage的值,而在表单每次提交时则清楚其值的例子
首先是一个表单:
HTML5 Local Storage Example
然后是js部分代码:
<script src="//code.jquery.com/jquery-latest.js"></script>
<script> <br>$(document).ready(function () { <br>/* <br>* 判断是否支持localstorage <br>*/ <br>if (localStorage) { <br>/* <br>* 读出localstorage中的值 <br>*/ <br>if (localStorage.type) { <br>$("#type").find("option[value=" + localStorage.type + "]").attr("selected", true); <br>} <br>if (localStorage.name) { <br>$("#name").val(localStorage.name); <br>} <br>if (localStorage.email) { <br>$("#email").val(localStorage.email); <br>} <br>if (localStorage.message) { <br>$("#message").val(localStorage.message); <br>} <br>if (localStorage.subscribe === "checked") { <br>$("#subscribe").attr("checked", "checked"); <br>} <br>/* <br>* 当表单中的值改变时,localstorage的值也改变 <br>*/ <br>$("input[type=text],select,textarea").change(function(){ <br>$this = $(this); <br>localStorage[$this.attr("name")] = $this.val(); <br>}); <br>$("input[type=checkbox]").change(function(){ <br>$this = $(this); <br>localStorage[$this.attr("name")] = $this.attr("checked"); <br>}); <br>$("form") <br>/* <br>* 如果表单提交,则调用clear方法 <br>*/ <br>.submit(function(){ <br>localStorage.clear(); <br>}) <br>.change(function(){ <br>console.log(localStorage); <br>}); <br>} <br>}); <br></script>











