Rumah >hujung hadapan web >tutorial js >使用jquery读取html5 localstorage的值的方法_jquery

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

WBOY
WBOYasal
2016-05-16 17:44:39959semak imbas

在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>
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn