JavaScript操作cookie实例

<script type="text/javascript">
var isHasCookei = getCookie("haveSave");    // 首先获取cookie  
console.log(isHasCookei);                   // 成功则打印yes  
if (!(isHasCookei == "yes")) {  
    setCookie("haveSave","yes",5000);// 如果加载完成就设置一个Cookie,执行一次该步骤  
}setCookie("haveSave","yes",50000);
console.log(document.cookie);

function setCookie(name,value,time) {       // 设置一个cookie  
    var exp = new Date();  
    exp.setTime(exp.getTime() + time*1);  
    document.cookie = name + "="+ value + ";expires=" + exp.toUTCString();  
}  

 
function getCookie(name) {                  //获取一个cookie  
    var strCookie = document.cookie;  
    var arr = strCookie.split(';');  
    for (var i = 0; i < arr.length; i++) {  
       var t = arr[i].split("=");  
        if(t[0] == name) {  
            return t[1];  
        }  
    };  
    return null;  
}  

function delCookie(name) {                   //删除一个cookie只需设置  expires为之前时间
    var exp = new Date();  
    exp.setTime(exp.getTime() - 1);  
    var cval=getCookie(name);  
    if(cval!=null)  
    document.cookie= name + "="+cval+";expires="+exp.toUTCString();  
}  
</script>

猜你喜欢

转载自blog.csdn.net/qq_38836082/article/details/79989823

相关文章