cookie封装//设置、获取、删除

cookie封装

    <script>
    window.onload=function (ev) {
        // var date=new Date();
        // date.setDate(date.getDate()+1);
        // document.cookie="age=33; expires="+date.toGMTString()+";";
        // document.cookie="age=33;name=ln;";
        // alert(document.cookie);

      // addCookie("wwe","99");
      //   addCookie("gender","99",7,"/");
        function addCookie(key,value,day,path,domain){
            // 1.处理默认保存的路径
            // if(!path){
            //     var index=window.location.pathname.lastIndexOf("/");
            //     var currentPath=window.location.pathname.slice(0,index);
            //     path=currentPath;
            // }
            var index=window.location.pathname.lastIndexOf("/");
            var currentPath=window.location.pathname.slice(0,index);
            path=path||currentPath;

            // 2.处理默认保存的时间
            domain=domain||document.domain;

            // 3.处理默认过期的时间
            if(!day){//没有输入day值的话
                document.cookie=key+"="+value+";path="+path+";domain="+domain+";";
            } else{
                var date=new Date();
                date.setDate(date.getDate()+day);
                document.cookie=key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
            }
        }

        function getCookie(key) {
            // console.log(document.cookie);
            var res=document.cookie.split(";");
            // console.log(res);
            for(var i=0;i<res.length;i++){
                // console.log(res[i]);
                var temp=res[i].split("=");
                // console.log(temp);

                // if(temp[0].trim()==="scroe"){
                //     console.log(temp[1]);
                // }

                if(temp[0].trim()===key){
                   return temp[1];
                }
        }
        }//封装
         console.log(getCookie("age"));

        // function delCookie(key) {
        //     addCookie(key,getCookie(key),-1);
        // }
        // delCookie("scroe");//可删除默认路径的值

        function delCookie(key, path) {
            addCookie(key,getCookie(key),-1,path);
        }
        delCookie("gender","/");//可删除修改后的路径(在删除的时候指定路径)
    }
</script>

可以更改key的值来实现封装;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值