Home >Web Front-end >JS Tutorial >Use js to read, write and delete cookie code continuation_javascript skills

Use js to read, write and delete cookie code continuation_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 16:29:181433browse

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:

Copy 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, 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.

Copy code The code is as follows:


shrink



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();
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn