温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js操作cookie与localStorage

发布时间:2020-06-28 15:45:50 来源:网络 阅读:316 作者:dforests 栏目:web开发

js操作cookie

var Cookie = {
setCookie: function(key, value, expiredays) {
expiredays = expiredays || 30; //默认30天 
var exdate = new Date();   
exdate.setDate(exdate.getDate() + expiredays);   
document.cookie = key + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
},
getCookie: function(key) {
var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null;
},
removeCookie: function(key) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = this.getCookie(key);
if(cval != null)
document.cookie = key + "=" + cval + ";expires=" + exp.toGMTString();
}
};
Cookie.setCookie('name', 'staven');
Cookie.removeCookie('name');
Cookie.getCookie('name');
</code>
使用localstorage存储数据

<code>
var LocalStorage = {
getLs: function(str) {
var msgArr = localStorage.getItem(str);
return !msgArr ? msgArr = [] : msgArr = msgArr.split(',');
},
/**

  • @param {String} key 键值
  • @param {String} str 须存入的内容,若存入多个用"/"隔开
  • @param {Number} num 最大存入的条数
    */
    setLs: function(key, str, num) {
    var msgArr = this.getLs(key);
    num = num || 10;
    str = str || '';
    if(str.indexOf("/") == -1 && msgArr.indexOf(str) == -1){
    msgArr.unshift(str);
    }else{
    var list = str.split('/');
    for(var i=0,len=list.length; i<len; i++){
    if(!!list[i] && msgArr.indexOf(list[i]) == -1){
    msgArr.unshift(list[i]);
    if(msgArr.length == num+1) return;
    }
    }
    }
    if(msgArr.length == num+1) {
    msgArr.pop();
    }
    msgArr = msgArr.join(',');
    localStorage.setItem(key, msgArr);
    },
    removeLs: function(str) {
    localStorage.removeItem(str);
    },
    clearLs: function(str) {
    localStorage.clear();
    }
    };
    LocalStorage.setLs('name',"staven", 10);
    //LocalStorage.setLs('name',"1/2/3/4/5/6", 8);
    console.log(LocalStorage.getLs('name'));
    //LocalStorage.removeLs('name');
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI