Cookie method encapsulation

cookie
 cookie: is a caching method:
            what is caching:
                    store a copy of the requested data for the convenience of next quick access

                    For example, many audio and video resources such as pictures, text, and video on the page are independently completed by the browser.


                    The purpose of caching is to improve access speed

            The use of cookies in js:
                    document.cookie


              The duration of the cookie: If                         the storage duration of the current cookie is not specified
                    when storing                             , it will default to one session                             as long as the browser does not close the cookie. Even if                             the browser tab is switched, the data will                             be different in the session. If the session switches tabs, the data will be lost                          . If the storage time of the cookie is set                             , the cookie will automatically expire after this time






  $("button").eq(0).click(function () {
        console.log(document.cookie);
    })

            store cookie
                document.cookie="key=value"
                document.cookie="key=value"
                document.cookie="key=value"

                Can only store one key-value pair at a time

  $("button").eq(1).click(function () {
        document.cookie="name=小砌墙";
        document.cookie="age=16";
        document.cookie="location=文化大厦";
        document.cookie="length=198";
    })

Cookies that are stored for a long time

    $("button").eq(2).click(function () {
//        存储带时长的
        var date=new Date();
        var ms=date.getTime()+1000*30;
//        console.log(ms);
        var futureDate=new Date(ms);//未来时间的Date格式  需要调用toGMTString()方法转换成GMT格式
 
 
        document.cookie="name=小砌墙";
        document.cookie="location=文化大厦; expires="+futureDate.toGMTString();
    })

            Extract all cookies: The format of
                document.cookie
                extraction is: key 1=value 1; key 2=value 2; key n=value n
                    is a string and we have to parse it ourselves

            Modify:
                document.cookie="Already stored key = new value";
                If the key does not exist, add a new key-value pair
                If the key already exists, modify the new value


             Delete cookie:
                Deleting a cookie requires life and death book (survival time)

                document.cookie="key=value; expires=a GMT time format"
                    GMT time format:
                            Wed Dec 04 2019 10:56:40 GMT+0800 (China Standard Time)
                            1575428424957


                    It doesn’t matter if you store the value once again for the key that has already been stored.
                    You must change the expiration time to the past tense before it can be deleted.
                        Regardless of whether the cookie has a duration or not, it will be automatically deleted as long as it is modified to the past tense.

                   document.cookie="key to delete=whatever; expires=a past time in GMT format"

Cookie method encapsulation

var cookie={
    //根据毫秒值返回未来时间的GMT格式
    getGMTString:function (ms) {
        if(typeof ms !="number"){
            return;
 
        }
    //    获取当前时间的毫秒值
        var nowMS=new Date().getTime();
        var futureDate=new Date(nowMS+ms);
        //把GMT格式返回
        return futureDate.toGMTString();
        
    },
 
 
    // 1.增加cookie  传入json进行批量增加
    /*
        expiresMS表示本次存储的cookie时长的毫秒值
        expiresMS是可选的  如果不传则 不指明时长
 
     */
    addItem:function (json,expiresMS) {
                            //5000 毫秒值
        if(!json){
            return;
        }
        for(var k in json){
            if(expiresMS && typeof expiresMS=="number"){
                document.cookie=k+"="+json[k]+"; expires="+this.getGMTString(expiresMS)
                        // document.cookie="name=小砌墙; expires=GMT格式";
            }else{
                //没有传第二个参数  那就没有时长 那就直接存储cookie
                document.cookie=k+"="+json[k];
            }
 
 
 
        }
        
    },
    
//    删除指定cookie  (根据键删除指定cookie)
    removeItem:function (key) {
        var cookie=document.cookie;
        if(!cookie){
            //如果本地cookie为空 就啥也别玩了
            return;
 
        }
    //    如果不为空 那么就直接设置一个新cookie 但是 时长为过去时
        //只要时长是过去时 那么既不会新增 又可以把原来的同一个键的删除
        document.cookie=key+"=随便; expires="+this.getGMTString(-1000);
 
        
    },
 
//    修改cookie
    modifyItem:function (oldkey,newVal) {
        var cookie=document.cookie;
        if(!cookie){
            //如果本地cookie为空 就啥也别玩了
            return false;
        }
        if(this.getAllCookies()[oldkey]!=undefined){
        //    如果键存在 那么就修改
            document.cookie=oldkey+"="+newVal;
 
            return true;
        }else{
            // 如果键不存在
            return false;
 
        }
 
 
 
 
    },
 
 
//    获取所有cookie返回json 
    getAllCookies:function () {
        var cookie=document.cookie;
        if(!cookie){
            //如果本地cookie为空 就啥也别玩了
            return "";
 
        }
        var json={};
        var arr=cookie.split(";");
        // console.log(arr);
        for(var i=0;i<arr.length;i++){
            //这个arr里面包含 key和value  newArr[0]是键 newArr[1]是值
            var newArr=arr[i].trim().split("=");
            // console.log(newArr);
            //把键值对放入json里面
            json[newArr[0]]=newArr[1]
            
        }
 
        return json;
 
 
        
    },
    //根据键获取指定的值
    getItem:function (key) {
        var cookie=document.cookie;
        if(!cookie){
            //如果本地cookie为空 就啥也别玩了
            return "";
 
        }
 
        return this.getAllCookies()[key];
 
 
 
    },
//    清空所有cookie
 
    clear:function () {
        this.addItem(this.getAllCookies(),-1000);
 
    }
 
    
    
    
    
 
}//对象结尾
/*
*   cookie的封装:
*       1.增加cookie  传入json进行批量增加
*
*       2.删除cookie  传入指定键  删除cookie
*
*       3.修改cookie  键不存在 则不修改 键存在再修改
*
*       4.获取所有cookie 返回json
*
*       5.获取单个cookie  传入键 获取指定cookie的值
*
*       6.清空所有cookie
*
*
*
* */
 
 
 
 
 
 

This article refers to the articles of other bloggers. Saving is convenient for searching. The following is the address

Web front-end-JavaScript--three common ways of local storage_Three ways of front-end local storage_yanghainan0318's blog-CSDN blog

Guess you like

Origin blog.csdn.net/dyx001007/article/details/130010370