美文网首页
Html5之localStorage

Html5之localStorage

作者: 陈川Lethe | 来源:发表于2017-01-06 18:49 被阅读25次

    localStorage是Html5新加入的特性,这个特性主要用来做浏览器本地存储

    一、判断浏览器是否支持localStorage

        if (!window.localStorage) {
            console.log("浏览器不支持localStorage")
        } else {
            console.log("浏览器支持localStorage")
        }
    

    二、往localStorage中写入内容:

        var DemoStorage = window.localStorage;
        //写入方法1:
        DemoStorage.name = "Tom";
        //写入方法2:
        DemoStorage["age"] = 18;
        //写入方法3:
        DemoStorage.setItem("hobby", "sport");
        
        console.log(DemoStorage.name,typeof DemoStorage.name);
        console.log(DemoStorage.age, typeof DemoStorage.age);
        console.log(DemoStorage.hobby, typeof DemoStorage.hobby);
        /*输出结果:
        Tom string
        18 string
        sport string*/
    

    以上的代码的例子中:age输入的是一个number,但是输出时是一个string,可见localStorage只能存储string类型的数据。

    三、localStorage的删除:

    1、删除localStorage中所有的内容:

    Storage.clear() 不接受参数,只是简单地清空域名对应的整个存储对象。

        var DemoStorage = window.localStorage;
        
        DemoStorage.name = "Tom";
        DemoStorage.age = 18;
        DemoStorage.hobby = "sport";
        
        console.log(DemoStorage);
        //输出:Storage {age: "18", hobby: "sport", name: "Tom", length: 3}
        DemoStorage.clear();
        console.log(DemoStorage);
        //输出: Storage {length: 0}
    

    2、删除某个健值对:

    Storage.removeItem() 接受一个参数——你想要移除的数据项的键,然后会将对应的数据项从域名对应的存储对象中移除。

        var DemoStorage = window.localStorage;
    
        DemoStorage.name = "Tom";
        DemoStorage.age = 18;
        DemoStorage.hobby = "sport";
    
        console.log(DemoStorage);
        //输出:Storage {age: "18", hobby: "sport", name: "Tom", length: 3}
        DemoStorage.removeItem("age");
        console.log(DemoStorage);
        //输出:Storage {hobby: "sport", name: "Tom", length: 2}
    

    四、参考资料:

    1、MDN火狐开发者中心——Window.localStorage

    2、MDN火狐开发者中心——使用 Web Storage API

    相关文章

      网友评论

          本文标题:Html5之localStorage

          本文链接:https://www.haomeiwen.com/subject/ajdxbttx.html