cookie练习

在user和pass中输入内容 点击保留登录 将他们保存在cookie中 关闭页面重新打开时 将用户名和密码自动输入这两个输入框 点击删除登录时 将输入框内容清空 并将cookie中的保留的用户名和密码删除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" name="user"/>
    <input type="password" name="pass">
    <button>保留登录</button>
    <button>删除登录</button>
    <script>
        // 在user和pass中输入内容 点击保留登录 将他们保存在cookie中 关闭页面重新打开时 将用户名和密码自动输入这两个输入框 点击删除登录时 将输入框内容清空 并将cookie中的保留的用户名和密码删除
        var aIn = document.getElementsByTagName("input");
        var aBtn = document.getElementsByTagName("button");
        if(getCookie("user")&&getCookie("pass")){
            aIn[0].value = getCookie("user");
            aIn[1].value = getCookie("pass");
        };
        aBtn[0].onclick = function (){
            setCookie("user",aIn[0].value,7);
            setCookie("pass",aIn[1].value,7);
        }
        aBtn[1].onclick = function (){
            removeCookie("user");
            removeCookie("pass");
            aIn[0].value = "";
            aIn[1].value = "";
        }












        // 设置cookie
        function setCookie(key,value,t){
            var oDate = new Date();
            oDate.setDate(oDate.getDate()+t);
            document.cookie = key+'='+encodeURI(value)+';expires='+oDate.toGMTString();
        }
        // decodeURI(document.cookie);获取cookie
        // 获取cookie
        function getCookie(key){
            var arr1 = document.cookie.split('; ');
            for(var i=0;i<arr1.length;i++){
                var arr2 = arr1[i].split('=');
                if(arr2[0]==key){
                    return decodeURI(arr2[1]);
                }
            }
        }
        // 删除cookie
        function removeCookie(key){
            setCookie(key,'',-1);
            // 设置和原来相同的key value 后设置的会覆盖先前的 所以将它变为空字符串 前一天过期
        }
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值