HTML5 localStorage本地存儲

首先天然是檢測瀏覽器是否支持本地存儲。在HTML5中,本地存儲是一個window的屬性,包括localStoragesessionStorage,從名字應該能夠很清楚的辨認兩者的區別,前者是一直存在本地的,後者只是伴隨着session,窗口一旦關閉就沒了。兩者用法徹底相同,這裏以localStorage爲例。javascript

if(window.localStorage){
 alert('This browser supports localStorage');
}else{
 alert('This browser does NOT support localStorage');
}php

 

存儲數據的方法就是直接給window.localStorage添加一個屬性,例如:window.localStorage.a 或者 window.localStorage["a"]。它的讀取、寫、刪除操做方法很簡單,是以鍵值對的方式存在的,以下:java

localStorage.a = 3;//設置a"3"
localStorage["a"] = "sfsf";//設置a"sfsf",覆蓋上面的值
localStorage.setItem("b","isaac");//設置b"isaac"
var a1 = localStorage["a"];//獲取a的值
var a2 = localStorage.a;//獲取a的值
var b = localStorage.getItem("b");//獲取b的值
localStorage.removeItem("c");//清除c的值
jquery

 

本身寫的例子:瀏覽器

<script type="text/javascript" src="jquery.js"></script>
<script> session

localStorage.a = 3;//設置a爲"3"
localStorage["a"] = "sfsf";//設置a爲"sfsf",覆蓋上面的值
localStorage.setItem("b","isaac");//設置b爲"isaac"

$(function(){spa

$(".kucun1").click(function(){
var a1 = localStorage["a"];//獲取a的值
var a2 = localStorage.a;//獲取a的值對象

alert(a1);
sessionStorage.setItem("a1", "sssss");
})
})ip

function txtName_change(v){
if(window.sessionStorage){
alert('This browser supports localStorage');
}else{
alert('This browser does NOT support localStorage');
}
//var strName =v.value;//獲取文本框內容
sessionStorage.setItem("strName",212); //調用setItem(key,value)方法,將內容保存至Session對象中鍵名爲strName
var a1 = sessionStorage.getItem("strName");
//$("#pStatus").text(sessionStorage.getItem("strName")); //經過鍵名獲取保存的內容,並經過key號傳到頁面(span標籤)中顯示
//alert(a1);
window.location.href="http://localhost:801/a.php";
}rem

//localStorage.a = 3;//設置a爲"3"
//localStorage["a"] = "sfsf";//設置a爲"sfsf",覆蓋上面的值
//localStorage.setItem("b","isaac");//設置b爲"isaac"
//var a1 = localStorage["a"];//獲取a的值
//var a2 = localStorage.a;//獲取a的值

</script>

<div class="kucun" id="dsd" onclick="txtName_change()">
dddddddddd
</div>

須要注意的是,HTML5本地存儲只能存字符串,任何格式存儲的時候都會被自動轉爲字符串,因此讀取的時候,須要本身進行類型的轉換

相關文章
相關標籤/搜索