In front-end development, we usually need to get and record some of the user's operation settings, so that users can visit the site next time without repeated adjustments to set the same function.
The method in this article is in the front-end development work in a group of their own to write a set of JS set and get the cookie method, can be used in many cases, did not do a fine digging and dig.
The complete code for the JS method is as follows:
varCookie = { Set: function (key,val,time) {//Set Cookie Method varDate=NewDate ();//Get current Time varExpiresdays=time;//set Date to n days afterDate.settime (Date.gettime () +expiresdays* -*3600* +);//time to format cookie recognitionDocument.cookie=key +"="+ val +"; expires="+date.togmtstring ();//Set Cookies }, Get: function (key) {//Get Cookie Method /*Get Cookie Parameters*/ varGetCookie = Document.cookie.replace (/[]/g,"");//gets the cookie and formats the obtained cookie, removing the space character varArrcookie = Getcookie.split (";")//The obtained cookie is identified with a "semicolon" to save the cookie to an array of Arrcookie varTips//declaring variable Tips for(varI=0; i<arrcookie.length;i++) {//use a For loop to find tips variables in cookies varArr=arrcookie[i].split ("=");//identify a single cookie with an "equal sign" and save a single cookie as an arr array if(key==arr[0]){//match the variable name, where arr[0] refers to the cookie name, and if the bar variable is a tips, perform the assignment in the Judgment statementtips=arr[1];//assigning the value of a cookie to a variable tips Break;//terminating A For loop traversal } } returntips; }}
The following is a simple way to set up and get the method to facilitate the front-end development of novice users to use
To set a cookie: Cookie.set (key,val,time)
Key can be understood as the variable name of a cookie
Val can be understood as the value of this cookie
Time is the timeout for the cookie, in days
The method to obtain a cookie is: Cookie.get (key)
Key is the cookie variable name we set up just now.
We only need to assign the function to the new variable to invoke this value, for example: var n = cookie.get (key);
method is not complicated to write, it is more suitable for the front-end development novice.
How do I debug and view cookies?
Cookies can be viewed by developer tools in some browsers, for example, in Chrome.
After you open the page, you can view information such as variable name, value, and Expiration time by "Right-click Review Element->resources" and then, for example, set a font-size
A set of methods for setting cookies through JS in front-end development