This article describes how jQuery operates the Cookie plug-in. For more information, see the following code:
The Code is as follows:
JQuery. cookie = function (name, value, options ){
If (typeof value! = 'Undefined') {// name and value given, set cookie
Options = options | {};
If (value = null ){
Value = '';
Options = $. extend ({}, options); // clone object since it's unexpected behavior if the expired property were changed
Options. expires =-1;
}
Var expires = '';
If (options. expires & (typeof options. expires = 'number' | options. expires. toUTCString )){
Var date;
If (typeof options. expires = 'number '){
Date = new Date ();
Date. setTime (date. getTime () (options. expires * 24*60*60*1000 ));
} Else {
Date = options. expires;
}
Expires = '; expires = 'date. toUTCString (); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options. path and options. domain
// In the following expressions, otherwise they evaluate to undefined
// In the packed version for some reason...
Var path = options. path? '; Path =' (options. path ):'';
Var domain = options. domain? '; Domain =' (options. domain ):'';
Var secure = options. secure? '; Secure ':'';
Document. cookie = [name, '=', encodeURIComponent (value), expires, path, domain, secure]. join ('');
} Else {// only name given, get cookie
Var cookieValue = null;
If (document. cookie & document. cookie! = ''){
Var cookies = document. cookie. split (';');
For (var I = 0; I <cookies. length; I ){
Var cookie = jQuery. trim (cookies [I]);
// Does this cookie string begin with the name we want?
If (cookie. substring (0, name. length 1) = (name' = ')){
CookieValue = decodeURIComponent (cookie. substring (name. length 1 ));
Break;
}
}
}
Return cookieValue;
}
};
Usage
The following describes how to use jQuery to operate the cookie plug-in:
$. Cookie (the _ cookie); // read the Cookie value
$. Cookie (the _ cookie, the _ value); // set the cookie value
$. Cookie (the _ cookie, the _ value, {expires: 7, path: '/', domain: 'jquery. com ', secure: true}); // create a cookie, including the Domain Name of the validity period path.
$. Cookie (the _ cookie, the _ value); // create a cookie
$. Cookie (the _ cookie, null); // delete a cookie
Set a cookie named blog with the value of css9.net:
$. Cookie ("blog", "css9.net ");
Set a cookie named "blog" with a value of css9.net, and set the expiration time (expires attribute) to 7 days:
$. Cookie ("blog", "css9.net", {expires: 7 });
Set a cookie named blog with a value of css9.net, set the expiration time (expires attribute) to 7 days, and set the path attribute of cookie to "/admin"
$. Cookie ("blog", "css9.net", {path: '/admin', expires: 7 });
Read Cookie:
Read the cookie value named blog:
Alert ($. cookie ("blog "));
Delete cookie:
$. Cookie ("example", null );