Use js to read, write, and delete Cookie codes.
In the last article, I used JavaScript to read, write, and delete Cookie code, share and describe in detail, and found some problems 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:
Copy codeThe 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.
Copy codeThe Code is as follows:
<Div class = "tab">
<H3 class = "tab-header"> shrink <Div class = "tab-con" id = "tabCon">
<P> show the content here after expansion </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 = 'login ';
}
Function hide (){
TabCon. style. display = 'none ';
Btn. setAttribute ('data-isclose', 'close ');
Btn. innerHTML = 'expand ';
}
Var flag = Cookie. get ('flag ');
If (flag = 'hide '){
Hide ();
}