Examples of cookie usage in jquery (acquisition, storage, deletion, etc.), jquerycookie

Source: Internet
Author: User
Tags set cookie

Examples of cookie usage in jquery (acquisition, storage, deletion, etc.), jquerycookie

This example describes how to use cookies in jquery. We will share this with you for your reference. The details are as follows:

Cookie has a specified cookie operation class in jquery. Next I will introduce some problems when using cookie operation classes, and then introduce the correct usage methods.

The following error occurs when you use JQuery to perform cookie operations:
The cookie has four different attributes:
Name, content, domain, path

$. Cookie (the _ cookie); // read cookie $. cookie (the _ cookie, the _ value); // store the cookie $. cookie (the _ cookie, the _ value, {expires: 7}); // store a cookie with a 7-day validity period $. cookie ('the _ cookies', '', {expires:-1}); // delete a cookie

Usage:
Copy codeThe Code is as follows: $. cookie ("currentMenuID", menuID );
The domain and path are not specified.

All cookie generated when the domain and path are different
Copy codeThe Code is as follows: $. cookie ("currentMenuID ");
An error occurs when the value is set.

Therefore:
Copy codeThe Code is as follows: $. cookie ("currentMenuID", "menuID", {path :"/"});
. The same cookieID in the same domain corresponds to a value.

Let's look at an instance.

Note that if path: '/' is not set, the path will be automatically set according to the directory [for example, http://www.xxx.com/user/, pathwill be set to '/user']

$. Extend ({/** 1. set the cookie value and set the value of the name variable to value example $. cookie ('name', 'value'); 2. create a cookie, including the Domain Name of the validity period and other example $. cookie ('name', 'value', {expires: 7, path: '/', domain: 'jquery. com ', secure: true}); 3. create cookie example $. cookie ('name', 'value'); 4. delete a cookie example $. cookie ('name', null); 5. get a cookie (name) value to myvar var account = $. cookie ('name'); **/cookieHelper: function (name, value, options ){ If (typeof value! = 'Undefined') {// name and value given, set cookie options = options |{}; if (value = null) {value = ''; 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 {d Ate = options. expires;} expires = '; expires =' + date. toUTCString (); // use expires attribute, max-age is not supported by IE} 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 ;}}});

Jquery operation Cookie records user query information

This is a list of Cookie data generation,

Each time you click query, a domain name is stored and the domain name for the last query is placed at the top. In this example, a maximum of 10 buckets can be stored. You can set them as needed.

Let's take a look at how it works.

First, write a JS file that operates the Cookie as follows:

Function getid (id) {return (typeof id = 'string ')? Document. getElementById (id): id}; function getOffsetTop (el, p) {var _ t = el. offsetTop; while (el = el. offsetParent) {if (el = p) break; _ t + = el. offsetTop} return _ t}; function getOffsetLeft (el, p) {var _ l = el. offsetLeft; while (el = el. offsetParent) {if (el = p) break; _ l + = el. offsetLeft} return _ l}; var currentInput = null; function BoxShow (e) {var input = e; if (! Input. id) {input = e.tar get? E.tar get: e. srcElement;} currentInput = input; FillUrls ("site"); var box = getid ("allSitesBoxHdl"); if (box. style. display = 'block' & currentInput. id = input. id) {return;} box. style. left = (getOffsetLeft (input) + 'px '; box. style. top = (getOffsetTop (input) + (input. offsetHeight-1) + 'px '; box. style. width = (input. offsetWidth-4) + 'px '; box. style. display = 'block';} function BoxShowUrls (e) {BoxShow (E);} function InputSetValue (val) {var obj = currentInput; obj. value = val; if (obj. getAttribute ('url') = 'true') {var tags = document. getElementsByTagName ('input'); for (var I = 0; I <tags. length; I ++) {if (tags [I]. getAttribute ('url') = 'true' & tags [I]! = Obj) {tags [I]. value = val ;}}boxhide () ;}// used for deletion. If you input a value to be deleted, you can delete function DelAllSitesValue (value) {var allSites = $. cookie ("site"); allSites = allSites. replace (value + "|", ""); $. cookie ("site", allSites, {expires: 7}); FillUrls ("site");} function BoxHide () {if (getid ("allSitesBoxHdl ")) {getid ("allSitesBoxHdl "). style. display = 'none'; }}// load list function FillUrls (cookieName) {var urls = $. cookie (cookieNam E); var html = ""; if (urls) {var urllist = urls. split ('|'); var forlength = 0; var stringcookie; for (var I = urllist. length-1; I> = 0; I --) {var textval = urllist [I]; if ($. trim (textval )! = "" & $. Trim (textval )! = "Undefined") {html + = "<li class =" lis "> <a href =" javascript: InputSetValue ('"+ textval + "'); ">" + textval + "</a> </li> <br/>"; forlength = forlength + 1; if (forlength> 10) {$. cookie ("site", stringcookie, {expires: 7}); break;} else {stringcookie = textval + "|" + stringcookie ;}}}} else {html + = "<li> no record </li>"} getid ("allSitesBoxContent "). innerHTML = html;} function closeIME (e) {var obj = e.tar get? E.tar get: e. srcElement; obj. style. imeMode = 'Disabled ';} function OnPaste (e) {var obj = e.tar get? E.tar get: e. srcElement; setTimeout ("MoveHttp ('" + obj. id + "')", 100);} function MoveHttp (id) {var val = getid (id ). value; val = val. replace ("http: //", ""); if (val [val. length-1] = '/') {val = val. substring (0, val. length-1);} getid (id ). value = val;} function OnKeyup (e) {var obj = e.tar get? E.tar get: e. srcElement; setTimeout ("addInput ('" + obj. id + "')", 200);} function addInput (id) {var obj = getid (id); // if it is an input without True, if (obj. getAttribute ('url') = 'true') {if (obj. value. indexOf ('. ')> 0) {obj. value = obj. value. replace ('. ','. ');} Var tags = document. getElementsByTagName ('input'); for (var I = 0; I <tags. length; I ++) {if (tags [I]. getAttribute ('url') = 'true' & tags [I]! = Obj) {tags [I]. value = obj. value ;}}} function Init () {$ ("# allSitesBoxHdl") [0]. style. display = 'none'; $ (": text "). each (function () {$ (this ). bind ("keyup", OnKeyup); $ (this ). bind ("mousedown", BoxShowUrls); $ (this ). bind ("mouseout", BoxHide); $ (this ). bind ("focus", closeIME); $ (this ). bind ("paste", OnPaste); $ (this ). bind ("mouseout", BoxHide); $ (this) [0]. setAttribute ('autocomplete', 'off') ;}); // extract Cookievar icpSite =$. cookie ("site"); if (icpSite) {// if the Cookie is not null, The icpSite = icpSite. split ('|') [0]; $ ("# site "). val (icpSite );}}

This effect is also included, that is, entering the values of multiple input boxes at the same time, as shown in

If the input box needs to use this effect, you only need to add an attribute url = "true", which is easy to operate. If you want to add an effect to the box, you can add this attribute, do not add url = "true" directly"
OK.

Add the following code on the interface with this effect:

<div style="display: none; position: absolute;" id="allSitesBoxHdl" class="classlist"  onmouseover="this.style.display='block'" onmouseout="this.style.display='none'">  <ul id="allSitesBoxContent">  </ul></div><script type="text/javascript">Init();</script>

In addition, JS files are directly put in a Js file. Just reference them.
How is the drop-down list loaded? You can see the following method.

Load list

Function FillUrls (cookieName) {var urls = $. cookie (cookieName); var html = ""; if (urls) {var urllist = urls. split ('|'); var forlength = 0; var stringcookie; for (var I = urllist. length-1; I> = 0; I --) {var textval = urllist [I]; if ($. trim (textval )! = "" & $. Trim (textval )! = "Undefined") {html + = "<li class =" lis "> <a href =" javascript: InputSetValue ('"+ textval + "'); ">" + textval + "</a> </li> <br/>"; forlength = forlength + 1; if (forlength> 10) {// here I only load 10 items. you can adjust it as needed $. cookie ("site", stringcookie, {expires: 7}); break ;} else {// if there are more than 10 stringcookies, take the last 10 stringcookies = textval + "|" + stringcookies ;}}}} else {html + = "<li> no record </li>"} getid ("allSitesBoxContent "). innerHTML = html ;}

After this is done, you only need to store the Cookie when you click query. See the following method.

Cookie operation

function setCookie(name, value) {var oldcookie = $.cookie(name);if (oldcookie == null) {$.cookie(name, value, { expires: 7 });} else {if ($.cookie(name).indexOf(value) == -1) {$.cookie(name, oldcookie + "|" + value, { expires: 7 });} else {$.cookie(name, oldcookie.replace(value, "") + "|" + value, { expires: 7 });}}FillUrls(name);}

Write data like this when calling
Copy codeThe Code is as follows: setCookie ("site", strdomin );
The function is completed.

Perform specific tests

The code is not very well written. I hope you will give more suggestions and we will make corresponding modifications to improve them.

A Cookie is stored on the client and can only access cookies under the same domain name. subdomains can access each other by adding the domain attribute. The storage method is as follows:
Copy codeThe Code is as follows: $. cookie ("domain", value, {expires: 7, domain: "7c.com "});
You can directly write $. cookie ("domain"); as long as it is a sub-domain name, it is called like this, so that the Cookie sharing function under the domain name can be achieved.

The effective use of cookies will bring N unexpected effects and functions to our website.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.