关于cookie

1.设置cookie:

   document.cookie = 'name = lc'

  docment.cookie = 'sex = man'

2.读取cookie:

  document.cookie

3.当存入多条cookie再直接输出cookie时输出方式为 每条的内容+"; "(分号加一个空格)的形式。

  alert(document.cookie);//输出  name = lc; sex = man;

4.设置cookie过期时间

var oDate = new Date();
    oDate.setDate(oDate.getDate() + 7);
        //cookie 不能包含对象,只能加入字符串,所以将这个时间转换为string,toGMTString是时间专用的转换字符串方法
    document.cookie = 'name=lc;expires=' + oDate.toGMTString();

5.特殊字符

在cookie中存入特殊字符需要特别的方法,如存入换行 \n 

  document.cookie = 'name=lc\n;expires=' + oDate.toGMTString(); //无法正确读取特殊字符
//使用encodeURI()和decodeURI()对特殊字符编码和解码
document.cookie = 'name=' + encodeURI('lc\n哈哈') + ';expires=' + oDate.toGMTString();

6.简单获取cookie,设置cookie,删除cookie

function setCookie(key,value,t){
        
        var oDate = new Date();
        oDate.setDate(oDate.getDate() + t);
        document.cookie = key + '=' + value + ';expires' + oDate.toGMTString();
        
    }
    function removeCookie(key) {
        
        setCookie(key,'',-1);
        
    }
    function getCookie(key){
        
        var arr1 = document.cookie.split("; ");
        for( var i = 0,len = arr.length; i<len; i++) {
            
            var arr2 = arr[i].split("=");
            if(arr2[0] == key) {
                
                return decodeURI(arr2[1]);
                
            }    
            
        }    
        
    }

 

转载于:https://www.cnblogs.com/SLEBEE/p/3984019.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值