Home > Article > Web Front-end > Detailed explanation of cookie usage examples in jquery (acquisition, storage, deletion, etc.)_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
Use:
All different cookies will be generated when the domain and path are different
So:
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? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } } });
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') ? 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 ? 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 ? e.target : e.srcElement; obj.style.imeMode = 'disabled'; } function OnPaste(e) { var obj = e.target ? 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 ? 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); } }
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>
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; }
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); }
Write like this when calling
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
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.