js设置 获取 删除cookie


function setCookie(key,value) {
        var date = new Date(),
                t = 5;
        date.setDate( date.getDate() + t );
        document.cookie = key+'='+encodeURIComponent(value)+';expires='+date.toGMTString();
    }
    // setCookie('username','liuwei');
    // setCookie('password','000000');
    // console.log(document.cookie);    //username=liuwei; password=000000
    // function getCookie(key) {
    //     var arr = document.cookie.split('; ');
    //     for (var i = 0; i < arr.length; i++) {
    //         var arr2 = arr[i].split('=');
    //         for (var j = 0; j < arr2.length; j++) {
    //             if (arr2[0] == key) {
    //                 return arr2[1];
    //             }
    //         };
    //     };
    // }
    function getCookie(key) {
        var arr,reg = RegExp('(^| )'+key+'=([^;]+)(;|$)');
        if (arr = document.cookie.match(reg))    //["username=liuwei;", "", "liuwei", ";"]
            return decodeURIComponent(arr[2]);
        else
            return null;
    }

    function delCookie(key) {
        var date = new Date();
        date.setTime(date.getTime() - 1);
        var delValue = getCookie(key);
        if (!!delValue) {
            document.cookie = key+'='+delValue+';expires='+date.toGMTString();
        }
    }
    delCookie('username');

    // console.log(document.cookie);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM