The operation of cookie cannot be performed on the cookie, that is, the read/write deletion operation. I will give you three examples to introduce the method of using js to operate the cookie. For more information, see.
Instance
// Set the cookie function. The first parameter is the cookie name, the second parameter is the value, and the third parameter is the cookie retention time (unit: Day)
The Code is as follows: |
Copy code |
Function setCookie (name, value, days ){ Var days = arguments [2]? Arguments [2]: 30; // if there are no days, this cookie is saved for 30 days by default. Var exp = new Date (); Exp. setTime (exp. getTime () + days * 86400000 ); Document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString (); } |
// Read the cookies Function
The Code is as follows: |
Copy code |
Function getCookie (name ){ Var arr = document. cookie. match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $ )")); If (arr! = Null ){ Return unescape (arr [2]); } Return null; } |
// Delete the cookie Function
The Code is as follows: |
Copy code |
Function delCookie (name ){ Var exp = new Date (); Exp. setTime (exp. getTime ()-1 ); Var cval = getCookie (name ); If (cval! = Null ){ Document. cookie = name + "=" + cval + "; expires =" + exp. toGMTString (); } } |
Encapsulated cookies:
The Code is as follows: |
Copy code |
Var cookie = new function (){ This. set = function (name, value, hours ){ Var life = new Date (). getTime (); Life + = hours * 1000*60*60; Var cookieStr = name + "=" + escape (value) + "; expires =" + new Date (life). toGMTString () + "; path = /"; Document. cookie = cookieStr; }; This. get = function (name ){ Var cookies = document. cookie. split (";"); Var I = 0; For (I = 0; I <cookies. length; I ++ ){ Var cookie2 = cookies [I]. split ("= "); If (cookie2 [0] = name) {return unescape (cookie2 [1]);} } Return ''; }; This. remove = function (name ){ Var cookieStr = name + "='' "+ escape ('null') +"; expires = "+ new Date (). toGMTString (); Document. cookie = cookieStr; }; } |