html5本地存储(Web Storage API)

1.浏览器可以存储5-10M内容,比以往的cookie4k容量高得多,注意是每个域名5M

2.localStorage.setItem ([string]key, [string]value);  //用localStorage对象的setItem方法存储键/值,注意键/值只能是字符串,数字或对象不能直接存储

3.    var sticky = localStorage.getItem("sticky_0");   //getItem方法提取值
    alert(sticky);

4.API得到广泛支持,甚至IE8都可以用,测试浏览器是否支持localStorage,查看window全局对象是否有一个localStorage属性

if (window ["localStorage"])

{ //code here }  

5.数字的存储,直接 localStorage.setItem ("numitems" , 1) ;   js会默认1为字符串 ,在取值的时候用parseInt() 或者 parseFloat() 函数进行数字转换 ,

var numItems = parseInt(localStorage.getItem("numitems"));

6.localStorage的数组写法,可以把它看作是一个数组,这样就不用setItem和getItem

localStorage["key1"] = "value1";

var sticky = localStorage["key1"];

7.localStorage的length 和 key方法的使用:

    for (var i = 0; i < localStorage.length; i++)
    {
        var key = localStorage.key(i);
        var value = localStorage[key];
        alert(value);
    }

    也可以使用for in循环

    for (var key in localStorage )

    { var value = localStorage[key]; }

8.清除数据 localStorage.clear(); 

9.每个浏览器的调试工具,在resource里可以看到localStorage可以编辑和删除

10.为了避免同一域名下key的混淆,可以给相同类的key创建一个数组,见完整代码

11.可以存储任何js对象和数组,用JSON的stringify 和 parse方法,来进行字符串和js对象/数组的转换

12.删除某一条 localStorage.remove(key) , 

13.sessionStorage 会话存储和localStorage一样,只不过它用于临时,关闭浏览器则清除

完整代码

window.onload = init;
localStorage.setItem("sticky_0", "Pick up dry cleaning");
localStorage.setItem("sticky_1", "Cancel cable tv, who needs it now?");
function init()
{
    var button = document.getElementById("add_button");
    button.onclick = createSticky;
    var stickiesArray = getStickiesArray();


    for (var i = 0; i < stickiesArray.length; i++)
    {
        var key = stickiesArray(i);
        var value = localStorage[key];
        addStickyToDom(value);
    }
}


function addStickyToDom (value)
{
    var stickies = document.getElementById("stickies");
    var sticky = document.createElement("li");
    var span = document.createElement("span");
    span.setAttribute("class", "sticky");
    span.innerHTML = value;
    sticky.appendChild(span);
    stickies.appendChild(sticky);
}


function createSticky()
{
    var stickiesArray = getStickiesArray();
    var currentDate = new Date();
    var time = currentDate.getTime();
    var key = "sticky_" + time;
    var value = document.getElementById("note_text").value;
    localStorage.setItem(key, value);
    stickiesArray.push(key);
    localStorage.setItem("stickiesArray", JSON.stringify(stickiesArray));
    addStickyToDom(value);
}


function getStickiesArray ()
{
    var stickiesArray = localStorage.getItem("stickiesArray");
    if (!stickiesArray)
    {
        stickiesArray = [];
        localStorage.setItem("stickiesArray", JSON.stringify(stickiesArray));
    }
    else
    {
        stickiesArray = JSON.parse(stickiesArray);
    }
    return stickiesArray;
}
/**
 * Created by andrewlee on 13-11-11.
 */





Note to Self








你可能感兴趣的:(Javascript,JS成品代码)