zoukankan      html  css  js  c++  java
  • js使用cookie存值和取值

    1.cookie中存值

    function setCookie (name, value) {
      if (value) {
        var Days = 365;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
      }
    }
    

    2.cookie中取值

    function getCookie(name){
      var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
      if(arr=document.cookie.match(reg)){
        return unescape(arr[2]);
      }else{
        return null;
      }
    }
    

    3.清除指定cookie

    function delCookie (name) {
      var exp = new Date();
      exp.setTime(exp.getTime() - 1);
      var cval = getCookie(name);
      if (cval && cval != null) {
        document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString();
      }
    }
    

    4.清除全部cookie

    function clearCookie () {
      var keys = document.cookie.match(/[^ =;]+(?==)/g)
      if (keys) {
        for (var i = keys.length; i--;) {
          document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
        }
      }
    }
    

    cookie中特殊字符处理:(分号(;)、逗号(,)、等号(=)以及空格)
    js对文字进行编码涉及3个函数:

    编码:escape,encodeURI,encodeURIComponent,
    解码:unescape,decodeURI,decodeURIComponent

  • 相关阅读:
    LFYZ-OJ ID: 1008 求A/B高精度值
    高精度运算
    【2018国庆雅礼集训】部分题解
    【模板】倍增求LCA
    Luogu1516 青蛙的约会
    loj #10043. 「一本通 2.2 例 1」剪花布条
    我太菜了
    Luogu1280 尼克的任务
    Luogu1091 合唱队形
    Luogu1006 传纸条
  • 原文地址:https://www.cnblogs.com/ZerlinM/p/13503689.html
Copyright © 2011-2022 走看看