Last article: Using js to read, write, delete cookie code sharing and detailed annotation instructions, I found some problems in practice:
1. Cookies can only be debugged on Firefox on local files, IE and Chrome are invalid
2. The cookie is not set to never expire. It only considers setting a time period and expires, which is obviously unreasonable.
This time, a more reasonable cookie operation code is given:
The code copy 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 cookies 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 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 Hide again. When the content is hidden, it will still be hidden next time it is opened, and when the content is displayed, it will still be displayed next time it is opened.
The code copy is as follows:
<div>
<h3>Shrink</h3>
<div id="tabCon">
<p>The content here can be seen after expanding</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 = 'Shrink';
}
function hide(){
tabCon.style.display = 'none';
btn.setAttribute('data-isClose','close');
btn.innerHTML = 'Expand';
}
var flag = Cookie.get('flag');
if(flag == 'hide'){
hide();
}