localStorage 方法存儲的數據沒有時間限制。次日、第二週或下一年以後,數據依然可用。javascript
用戶訪問頁面的次數進行計數:java
1 <script type="text/javascript"> 2 if (localStorage.pagecount) 3 { 4 localStorage.pagecount=Number(localStorage.pagecount) +1; 5 } 6 else 7 { 8 localStorage.pagecount=1; 9 } 10 document.write("Visits "+ localStorage.pagecount + " time(s)."); 11 </script>
localStorage 存儲JSON數據的簡單實例瀏覽器
//定義JSON格式的字符串
var userData={
name:"paul",
account:"paul",
level:1
}
//存儲userData數據
localStorage.setItem("userData",JSON.stringify(userData));
//讀取userData數據並賦給新變量newuserData
var newuserData=JSON.parse(localStorage.getItem("userData"));
//刪除本地存儲的item
localStorage.removeItem("userData");
sessionStorage 方法針對一個 session 進行數據存儲。當用戶關閉瀏覽器窗口後,數據會被刪除。session
下面的例子對用戶在當前 session 中訪問頁面的次數進行計數:this
1 <script type="text/javascript"> 2 if (sessionStorage.pagecount) 3 { 4 sessionStorage.pagecount=Number(sessionStorage.pagecount) +1; 5 } 6 else 7 { 8 sessionStorage.pagecount=1; 9 } 10 document.write("Visits "+sessionStorage.pagecount+" time(s) this session."); 11 </script>