This article is the previous article "Sharing Cookie code with js reading, writing, and deleting, and providing detailed comments", which finds some problems and analyzes and solves them. We recommend this article to you: using js to read, write, and delete Cookie code, share and describe the code in detail. Some problems have been found in practice:
1. Cookies can only be debugged on Firefox on local files, and IE and chrome are invalid.
2. The cookie is not set to never expire. It is obviously not reasonable to set a period of time to expire.
The following is a reasonable cookie operation code:
The Code is as follows:
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, the cookie will never expire.
Document. cookie = k + "=" + v + "; expires =" + (e! = ''? Date. toGMTString (): "GMT_String") + "; path =/; domain =" + (d | '');
},
Del: function (k ){
Var date = new Date ();
// Set date to the past time
Date. setTime (date. getTime ()-10000 );
Document. cookie = k + "=; expires =" + date. toGMTString ();
}
};
In this example, click "Expand content" and click "hide" again. When the content is hidden, it is opened or hidden next time. When the content is displayed, it is displayed next time.
The Code is as follows:
Shrink
After expansion, the content here is displayed.
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 = 'login ';
}
Function hide (){
TabCon. style. display = 'none ';
Btn. setAttribute ('data-isclose', 'close ');
Btn. innerHTML = 'expand ';
}
Var flag = Cookie. get ('flag ');
If (flag = 'hide '){
Hide ();
}