在HTML 5中,localstorage是个不错的东西,在支持localstorage的浏览器中, 能持久化用户表单的输入,即使关掉浏览器,下次重新打开浏览器访问,也能读出其值, 下面给出的例子是使用jquery 在每次表单加载的时候,读localstorage的值,而在表单每次提交时则清楚其值的例子
首先是一个表单:
HTML5 Local Storage Example HTML5 Local Storage Example
然后是js部分代码:
<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>