Last article: Using js to read, write, and delete cookie code sharing and detailed comments , some problems were discovered in practice:
1. Cookies on local files can only be debugged on Firefox, and are invalid for IE and chrome
2. The cookie is not set to never expire. It is only considered to set a time period before it expires, which is obviously unreasonable.
This time we give a more reasonable cookie operation code:
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, the cookie will be used 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 date to the past time
date.setTime(date.getTime()-10000);
document.cookie=k "=; expires=" date.toGMTString();
}
};
The example demonstrates: click on the text to expand the content, and click again to hide it. When the content is hidden, it will still be hidden next time it is opened. When the content is displayed, it will still be displayed next time it is opened.
After expansion, you can see the content here
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 = 'Shrink';
}
function hide(){
tabCon.style.display = 'none';
btn.setAttribute('data-isClose','close');
btn.innerHTML = 'Expand';
}
var flag = Cookie.get('flag');
if(flag == 'hide'){
hide();
}