cookie|javascript| objects
1. Create a Cookie Object
Because it is used as a class name or namespace, it is similar to the Math object, where a cookie is used to represent the object
var Cookie = new Object ();
2, to implement the method of setting cookies
//name is the name of the cookie to set; value is the value of the cookie, option includes the other option, an object as a parameter
Cookie.setcookie = function (name, value, (option) {
//To store the cookie format string assigned to Document.cookie
var str = name+ "=" +escape (value);
if (option) {
//If an expiration is set
if (option.expiredays) {
var date = new Date ();
var ms = option.expiredays*24*3600*1000;
Date.settime (Date.gettime () +ms);
str + = "; Expires= "+date.togmtstring ();
}
if (option.path) str + = "; Path= "+path;//set access Path
if (option.domain) str + ="; Domain= "+domain;//set access host
if (option.secure) str + ="; True ';/set security
}
document.cookie = str;
}
3, how to implement cookies
Name to specify the names of the cookies to return the corresponding values based on the name
Cookie.getcookie = function (name) {
var Cookiearray = Document.cookie.split (";"); /Get the split cookie name value pair
var cookie = new Object ();
for (var i=0; i<cookiearray.length; i++) {
var arr = cookiearray[i].split ("=");//separate name and value
if (arr[0]==name) return unescape (arr[1]);//If it is a specified cookie, it returns its value
}
Return "";
}
4, the implementation of the method of deleting cookies
Name is the name of the specified cookie, which deletes the corresponding cookie according to the name. In the implementation, the deletion of the cookie is done by calling Setcookie, which assigns the Expiredays property of option to a negative number
Cookie.deletecookie = function (name) {
This.setcookie (Name, "", {expiredays:-1});//Set the expiration time to the past to remove a cookie
}
With the following code, after the entire cookie object is created, you can place it in a curly brace to define:
var Cookie = {
Setcookie:function () {},
Getcookie:function () {},
Deletecookie:function () {}
}
In this form, you can make the cookie function more clear, it as a global object, greatly facilitate the operation of cookies
Cookie.setcookie ("User", "Terry");
Cookie.deletecookie ("user");