I wrote a general OOByClassCookie when I was working on the project some days ago. I will share it with you today! If you have better insights, you can discuss it!
The Code is as follows:
/*
* Js Class Cookie
* Author: Mr Co
*/
Var Cookie = function (/* Cookie name */name ){
This. $ name = name;
Var allcookies = document. cookie;
If (allcookies = '') return;
Var cookies = allcookies. split (';');
Var cookie = null;
For (var I = 0; I <cookies. length; I ++ ){
If (cookies [I]. substring (0, name. length + 1) = (name + '= ')){
Cookie = cookies [I];
Break;
}
}
If (cookie = null) return;
Var cookieval = cookie. substring (name. length + 1 );
Var a = cookieval. split ('&');
For (var I = 0; I <a. length; I ++ ){
A [I] = a [I]. split (':');
}
For (var I = 0; I <a. length; I ++ ){
This [a [I] [0] = decodeURIComponent (a [I] [1]);
}
}
/*
* Save Cookie Data Objects
*/
Cookie. prototype. store = function (/* expiration time (1 indicates one day and so on) */daysToLive,/* Current Cookie valid address */path,/* Current Cookie valid domain name access */domain, /* Security */secure ){
Var cookieval = '';
For (var prop in this ){
If (prop. charAt (0) = '$') | (typeof this [prop]) = 'function') continue;
If (cookieval! = '') Cookieval + = '&';
Cookieval + = prop + ':' + encodeURIComponent (this [prop]);
}
Var cookie = this. $ name + '=' + cookieval;
If (daysToLive | daysToLive = 0 ){
Cookie + = '; max-age =' + (daysToLive * 24*60*60 );
}
If (path) cookie + = '; path =' + path;
If (domain) cookie + = '; domain =' + domain;
If (secure) cookie + = '; secure ';
Document. cookie = cookie;
}
/*
* Remove the specified attribute of the Cookie data object.
*/
Cookie. prototype. remove = function (/* Current Cookie valid address */path,/* Current Cookie valid domain name access */domain,/* Security */secure ){
For (var prop in this ){
If (prop. charAt (0 )! = '$' & Typeof this [prop]! = 'Function') delete this [prop];
}
This. store (0, path, domain, secure );
}
/*
* Verify whether the current client browser supports cookies
*/
Cookie. IsAllowCookie = function (){
If (! Navigator. cookieEnabled ){
Alert ('note: \ n your browser has disabled page cookies currently! This may cause you to lose the selected food data when refreshing the page during \ n \ r \ n selection of Food Data! \ R \ n we recommend that you enable browser cookies! ');
Return false;
}
Return true;
}
Test JS DEMO
The Code is as follows:
Function testFn (){
Var cookie = new Cookie ('test ');
If (! Cookie. name |! Cookie. color ){
Cookie. name = prompt ('What is your name :','');
Cookie. color = prompt ('What is your favorite color :','');
}
If (! Cookie. visits) cookie. visits = 1;
Else cookie. visits ++;
Cookie. store (10 );
Alert ('color: '+ cookie. color + 'name:' + cookie. name + 'visits: '+ cookie. visits );
}