Js to read write delete Cookie code sequels

  • 2020-03-30 04:30:39
  • OfStack

In a previous post: (link: #), some problems were found in practice:

Cookies on local files can only be debugged on firefox, IE and chrome are not valid

2. Cookie is not set to never expire, and it is not reasonable to set it to expire after a certain period of time.

This time, the reasonable cookie operation code is given:


var Cookie = {
    get: function (k) {
        return ((new RegExp(["(?:; )?", k, "=([^;]*);?"].join(""))).test(document.cookie) && RegExp["$1"]) || "";
    },
    set: function (k, v, e, d) {
        var date=new Date();
        var expiresDays=e;
        date.setTime(date.getTime()+expiresDays*24*3600*1000);
        //If there is a set time, use the cookie within the specified time, otherwise it will never expire
        document.cookie=k+"="+v+"; expires="+ (e != '' ? date.toGMTString(): "GMT_String")+";path=/;domain="+ (d||'');
    },
    del: function (k) {
        var date=new Date();
        //Set the date to the past time
        date.setTime(date.getTime()-10000);
        document.cookie=k+"=; expires="+date.toGMTString();
    }
};

Example: click text to expand the content, and then click hide again. When the content is hidden, it will be hidden next time. When the content is displayed, it will be displayed next time.


<div class="tab">
 <h3 class="tab-header"> shrinkage </h3>
 <div class="tab-con" id="tabCon">
  <p> And then you can see what's going on here </p>
 </div>
</div>
var btn = document.getElementsByTagName('h3')[0];
btn.addEventListener('click',function(){
 var isClose = this.getAttribute('data-isClose');
 if(isClose == 'close'){
  show();
  Cookie.del('flag');
 }else{
  hide();
  Cookie.set('flag','hide');
 }
});
var tabCon = document.getElementById('tabCon');
function show(){
 tabCon.style.display = 'block';
 btn.setAttribute('data-isClose','open');
 btn.innerHTML = ' shrinkage ';
}
function hide(){
 tabCon.style.display = 'none';
 btn.setAttribute('data-isClose','close');
 btn.innerHTML = ' an ';
}
var flag = Cookie.get('flag');
if(flag == 'hide'){
 hide();
}


Related articles: