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;
        //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
        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>
var btn = document.getElementsByTagName('h3')[0];
 var isClose = this.getAttribute('data-isClose');
 if(isClose == 'close'){
var tabCon = document.getElementById('tabCon');
function show(){
 tabCon.style.display = 'block';
 btn.innerHTML = ' shrinkage ';
function hide(){
 tabCon.style.display = 'none';
 btn.innerHTML = ' an ';
var flag = Cookie.get('flag');
if(flag == 'hide'){

Related articles: