


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:
When the domain and path are not specified.
All different cookies will be generated when the domain and path are different
Problems arise when taking values.
So:
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? 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
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
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.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment
