js操作cookie

本文提供了一个使用JavaScript进行Cookie操作的示例,包括设置、获取和删除Cookie的功能,并通过按钮触发这些操作。演示了如何设置Cookie的有效期,以及有效期对Cookie的影响。

js本地化操作,设置cookie、获取cookie,删除cookie的例子:

参考网站:w3c js操作cookie

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<button id="btn1" onclick="setCookies()">设置cookies</button>
<button id="btn2" onclick="getCookies()">读取cookies</button>
<button id="btn3" onclick="clearCookies()">清除cookies</button>
</body>
<script type="text/javascript">
function setCookies(){
    setCookie('name', 'zhangsan');
    setCookie('password', '123456', 2);
    setCookie('age', '12');
}

function getCookies(){
    var name = getCookie('name');
    var password = getCookie('password');
    var age = getCookie('age');
    console.log("name:"+name+" password:"+password+" age:"+age);
}

function clearCookies(){
    deleteCookie('name');
    deleteCookie('age');
    deleteCookie('password');
}

/**
 * 设置cookie 键值对形式
 * name 存储的key
 * value 对应的值
 * expiredays 过期时间 天数  如果为null的话不设置过期时间
 * 不设置这个值的话,cookie默认在关闭浏览器时失效
 */
function setCookie(name, value, expiredays){
    var exdate=new Date();
    if(expiredays==null || typeof(expiredays)=='undefined'){
        document.cookie = name + "="+escape(value);
    }else{
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie = name + "="+escape(value)+";expires="+exdate.toGMTString();
    }
}

/**
 * 读取cookie
 */
 function getCookie(name){
    if(document.cookie.length>0){
        var start = document.cookie.indexOf(name + "=");
        if(start != -1){
            start = start + name.length + 1;
            end = document.cookie.indexOf(";",start);
            if(end == -1){
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(start, end));
        }
    }
    return null;
}

/**
 * 删除cookie
 */
 function deleteCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1000); //当前时间减去一秒,相当于立即过期(可以增减)
    var val = getCookie(name);
    if(val!=null){
        document.cookie = name + "="+val+";expires="+exp.toGMTString();
    }
}
</script>
</html>
password设置了过期时间,看设置过期时间与不设置过期时间的区别:


 

转载于:https://www.cnblogs.com/tenWood/p/6725878.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值