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

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

WBOY
WBOY原創
2016-05-16 17:44:39959瀏覽

在HTML 5中,localstorage是個不錯的東西,在支援localstorage的瀏覽器中, 能持久化用戶表單的輸入,即使關掉瀏覽器,下次重新打開瀏覽器訪問,也能讀出其值, 下面給出的例子是使用jquery 在每次表單載入的時候,讀localstorage的值,而在表單每次提交時則清楚其值的例子
首先是一個表單

複製代碼 代碼如下:











HTML5 Local Storage Example





HTML5 Local Storage Example




Enquiry Form
















div>














然後是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); <BR>} <BR>if (localStorage.subscribeStorage. === "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>}change) <BR>.change (function(){ <BR>console.log(localStorage); <BR>}); <BR>} </script>
});
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn