美文网首页
js cookie,sessionStorage,localSt

js cookie,sessionStorage,localSt

作者: 躺在家里干活 | 来源:发表于2019-10-22 10:08 被阅读0次

sessionStorage

// 设置
sessionStorage.setItem(name, val);
// 获取
sessionStorage.getItem(name);
// 删除
sessionStorage.removeItem(name);
// 清空
sessionStorage.clear();

localStorage

// 设置
localStorage.setItem(name, val);
// 获取
localStorage.getItem(name);
// 删除
localStorage.removeItem(name);
// 清空
localStorage.clear();

cookie

// 设置cookie
function setCookie(cname,cvalue,exdays){
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

// 获取cookie
// 方法一:
function getCookie(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
    }
    return "";
}
// 方法二:
function getCookie(n){
    var m = document.cookie.match(new RegExp("(^| )"+n+"=([^;]*)(;|$)"));
    return !m?’’:decodeURIComponent(m[2]);
}

// 检测cookie
function checkCookie(){
    var user=getCookie("username");
    if (user!=""){
        alert("欢迎 " + user + " 再次访问");
    }
    else {
        user = prompt("请输入你的名字:","");
          if (user!="" && user!=null){
            setCookie("username",user,30);
        }
    }
}

// 删除cookie中指定变量
function delCookie(name){
    var expire = (new Date(0)).toGMTString()
    document.cookie=name+"=; expires="+expire;
}

// 清除所有cookie
clearAllCookie() {
  // 过期时间
  var expire = (new Date(0)).toGMTString()
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length - 1; i--;) {
      document.cookie = keys[i] + "=; expire=" + expire + "; path=/";
    }
  }
}

个人博客

相关文章

网友评论

      本文标题:js cookie,sessionStorage,localSt

      本文链接:https://www.haomeiwen.com/subject/pgnfvctx.html