Home Web Front-end JS Tutorial Detailed explanation of cookie usage examples in jquery (acquisition, storage, deletion, etc.)_jquery

Detailed explanation of cookie usage examples in jquery (acquisition, storage, deletion, etc.)_jquery

May 16, 2016 pm 03:21 PM
cookie jquery

The examples in this article describe the usage of cookies in jquery. Share it with everyone for your reference, the details are as follows:

Cookie has a designated cookie operation class in jquery. Let me first introduce some problems when we use cookie operation classes, and then introduce the correct usage method.

When using JQuery to operate cookies, an incorrect value occurs:
It turns out that cookies have four different attributes:
name, content, domain, path

$.cookie('the_cookie'); // 读取 cookie 
$.cookie('the_cookie', 'the_value'); // 存储 cookie 
$.cookie('the_cookie', 'the_value', { expires: 7 }); // 存储一个带7天期限的 cookie 
$.cookie('the_cookie', '', { expires: -1 }); // 删除 cookie

Copy after login

Use:

Copy code The code is as follows:
$.cookie("currentMenuID", menuID);

When the domain and path are not specified.

All different cookies will be generated when the domain and path are different

Copy code The code is as follows:
$.cookie("currentMenuID");

Problems arise when taking values.

So:

Copy code The code is as follows:
$.cookie("currentMenuID", "menuID", { path: "/" });

to cover. The same cookieID in the same domain corresponds to a value.

Let’s take a look at an example

Note about the path setting of cookies. If path:'/' is not set, the path will be automatically set according to the directory [such as: http://www.xxx.com/user/, the path will be set to ' /user']

$.extend({ 
/** 
 1. 设置cookie的值,把name变量的值设为value  
example $.cookie('name', ‘value'); 
 2.新建一个cookie 包括有效期 路径 域名等 
example $.cookie('name', ‘value', {expires: 7, path: ‘/', domain: ‘jquery.com', secure: true}); 
3.新建cookie 
example $.cookie('name', ‘value'); 
4.删除一个cookie 
example $.cookie('name', null); 
5.取一个cookie(name)值给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 { 
          date = 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&#63; 
          if (cookie.substring(0, name.length + 1) == (name + '=')) { 
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
            break; 
          } 
        } 
      } 
      return cookieValue; 
    } 
  } 
});

Copy after login

Jquery operation cookie records the information the user has queried

This is a list generated by Cookie data,

Each time you click to query, a domain name will be stored, and the last domain name queried will be placed at the top. This example can store up to 10 items, you can set them according to your own situation

Let’s take a look at how to achieve it

First write a JS file to operate Cookie as follows

function getid(id) {
return (typeof id == 'string') &#63; 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.target &#63; e.target : 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();
}
//删除时使用,传入一个要删除的值就可以删除
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';
}
}
//加载列表
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) {
$.cookie("site", stringcookie, { expires: 7 });
break;
} else {
stringcookie = textval + "|" + stringcookie;
}
}
}
} else {
html += "<li>没有记录</li>"
}
getid("allSitesBoxContent").innerHTML = html;
}
function closeIME(e) {
var obj = e.target &#63; e.target : e.srcElement;
obj.style.imeMode = 'disabled';
}
function OnPaste(e) {
var obj = e.target &#63; e.target : 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.target &#63; e.target : e.srcElement;
setTimeout("addInput('" + obj.id + "')", 200);
}
function addInput(id) {
var obj = getid(id);
//如果是一个没有True的input不执行
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');
});
//取出Cookie
var icpSite = $.cookie("site");
if (icpSite) {
//取出Cookie不为空的话就给当前框
icpSite = icpSite.split('|')[0];
$("#site").val(icpSite);
}
}

Copy after login

This also comes with the effect of inputting the values ​​​​of multiple input boxes at the same time, as shown below

If you want to use this effect in that input box, just add an attribute as url="true", which is convenient and operable. If you want to add an effect to that box, just add this attribute. If you don't want to add it, just don't add it. url="true"
That's OK.

Add the following code to the interface that uses 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>

Copy after login

Place the other JS directly in a Js file and just quote it in
How is the drop-down list loaded? Just look at one of the methods below to find out

Loading 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) {//在这里我只加载10条,大家可以根据自己的情况进行调整
$.cookie("site", stringcookie, { expires: 7 });
break;
} else {//如果超出10个的话就取最后10个
stringcookie = textval + "|" + stringcookie;
}
}
}
} else {
html += "<li>没有记录</li>"
}
getid("allSitesBoxContent").innerHTML = html;
}

Copy after login

After completing this, we only need to store the cookie when we click the query. See the method below

Operating Cookie Class

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);
}

Copy after login

Write like this when calling

Copy code The code is as follows:
setCookie("site", strdomin);

Ok the function is completed.

Conduct specific tests

The code is not very well written. I hope you can give me more suggestions so that we can make corresponding modifications and strive to improve it.

Cookies are stored on the client side. One cookie can only access cookies under the same domain name. Subdomain names can access each other. Just add the domain attribute. The storage method is as follows

Copy code The code is as follows:
$.cookie("domain", value, { expires: 7, domain: " 7c.com" });

Just write $.cookie("domain"); to get the time. As long as it is a subdomain name, you can call it like this, so that you can achieve the cookie sharing function under this domain name.

The effective use of cookies will bring many unexpected effects and functions to our website, please share with us

For more information about jQuery’s cookie operation, please view this site’s special topic: " Summary of jQuery’s cookie operation skills "

I hope this article will be helpful to everyone in jQuery programming.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles