标签:style http io ar color os sp java on
首先自然是检测浏览器是否支持本地存储。在HTML5中,本地存储是一个window的属性,包括localStorage和sessionStorage,从名字应该可以很清楚的辨认二者的区别,前者是一直存在本地的,后者只是伴随着session,窗口一旦关闭就没了。二者用法完全相同,这里以localStorage为例。
if(window.localStorage){
alert(‘This browser supports localStorage‘);
}else{
alert(‘This browser does NOT support localStorage‘);
}
存储数据的方法就是直接给window.localStorage添加一个属性,例如:window.localStorage.a 或者 window.localStorage["a"]。它的读取、写、删除操作方法很简单,是以键值对的方式存在的,如下:
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的值
自己写的例子:
<script type="text/javascript" src="jquery.js"></script>
<script>
localStorage.a = 3;//设置a为"3"
localStorage["a"] = "sfsf";//设置a为"sfsf",覆盖上面的值
localStorage.setItem("b","isaac");//设置b为"isaac"
$(function(){
$(".kucun1").click(function(){
var a1 = localStorage["a"];//获取a的值
var a2 = localStorage.a;//获取a的值
alert(a1);
sessionStorage.setItem("a1", "sssss");
})
})
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";
}
//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本地存储只能存字符串,任何格式存储的时候都会被自动转为字符串,所以读取的时候,需要自己进行类型的转换
标签:style http io ar color os sp java on
原文地址:http://www.cnblogs.com/you-jia/p/4137049.html