首页 >web前端 >js教程 >使用jquery读取html5 localstorage的值的方法_jquery

使用jquery读取html5 localstorage的值的方法_jquery

WBOY
WBOY原创
2016-05-16 17:44:39952浏览

在HTML 5中,localstorage是个不错的东西,在支持localstorage的浏览器中, 能持久化用户表单的输入,即使关掉浏览器,下次重新打开浏览器访问,也能读出其值, 下面给出的例子是使用jquery 在每次表单加载的时候,读localstorage的值,而在表单每次提交时则清楚其值的例子
首先是一个表单

复制代码 代码如下:





HTML5 Local Storage Example





HTML5 Local Storage Example




Enquiry Form




































然后是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>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn