在HTML 5中,localstorage是個不錯的東西,在支援localstorage的瀏覽器中, 能持久化用戶表單的輸入,即使關掉瀏覽器,下次重新打開瀏覽器訪問,也能讀出其值, 下面給出的例子是使用jquery 在每次表單載入的時候,讀localstorage的值,而在表單每次提交時則清楚其值的例子首先是一個表單: 複製代碼 代碼如下: HTML5 Local Storage Example HTML5 Local Storage Example Enquiry Form Type of enquiry Please select General Sales Support Name Email Address div> Message Subscribe to our newsletter 然後是js部分代碼: 複製代碼 代碼如下: <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>} });