jquery中cookie用法實(shí)例詳解(獲取,存儲(chǔ),刪除等)
本文實(shí)例講述了jquery中cookie用法。分享給大家供大家參考,具體如下:
cookie在jquery中有指定的cookie操作類(lèi),下面我先來(lái)介紹我們?cè)谑褂胏ookie操作類(lèi)時(shí)的一些問(wèn)題,然后介紹正確的使用方法。
使用JQuery操作cookie時(shí) 發(fā)生取的值不正確的問(wèn)題:
結(jié)果發(fā)現(xiàn)cookie有四個(gè)不同的屬性:
名稱(chēng),內(nèi)容,域,路徑
$.cookie('the_cookie'); // 讀取 cookie
$.cookie('the_cookie', 'the_value'); // 存儲(chǔ) cookie
$.cookie('the_cookie', 'the_value', { expires: 7 }); // 存儲(chǔ)一個(gè)帶7天期限的 cookie
$.cookie('the_cookie', '', { expires: -1 }); // 刪除 cookie
使用:
時(shí) 未指定域和路徑。
所有當(dāng)域和路徑不同時(shí)會(huì)產(chǎn)生不同的cookie
取值時(shí)會(huì)產(chǎn)生問(wèn)題。
故:
進(jìn)行覆蓋。同域下同一個(gè)cookieID對(duì)應(yīng)一個(gè)值。
下面我們來(lái)看個(gè)實(shí)例
關(guān)于cookie的path設(shè)置需要注意,如果不設(shè)置path:'/'的話,path則會(huì)根據(jù)目錄自動(dòng)設(shè)置[如:http://www.xxx.com/user/,path會(huì)被設(shè)置為 '/user']
$.extend({
/**
1. 設(shè)置cookie的值,把name變量的值設(shè)為value
example $.cookie('name', ‘value');
2.新建一個(gè)cookie 包括有效期 路徑 域名等
example $.cookie('name', ‘value', {expires: 7, path: ‘/', domain: ‘jquery.com', secure: true});
3.新建cookie
example $.cookie('name', ‘value');
4.刪除一個(gè)cookie
example $.cookie('name', null);
5.取一個(gè)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操作Cookie記錄用戶查詢過(guò)信息

這是一個(gè)Cookie數(shù)據(jù)生成的列表,
每次單擊查詢會(huì)存儲(chǔ)一個(gè)域名,并把最后一次查詢的域名放在最上方。本例子最多存儲(chǔ)10個(gè),大家可以根據(jù)自己情況進(jìn)行設(shè)置
下在咱們一起來(lái)看看是怎么實(shí)現(xiàn)的吧
先寫(xiě)一個(gè)操作Cookie的JS文件如下
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();
}
//刪除時(shí)使用,傳入一個(gè)要?jiǎng)h除的值就可以刪除
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>沒(méi)有記錄</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);
//如果是一個(gè)沒(méi)有True的input不執(zhí)行
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不為空的話就給當(dāng)前框
icpSite = icpSite.split('|')[0];
$("#site").val(icpSite);
}
}
在這里面還附帶了這樣一個(gè)效果,就是同時(shí)輸入多個(gè)輸入框的值,如下圖

如果那個(gè)輸入框要使用這樣的效果只要添加一個(gè)屬性為url="true"就行了,這樣方便 可操作性強(qiáng),想給那個(gè)框加效果就加上這個(gè)屬性,不想加的直接不加url="true"
就OK了。
在使用這個(gè)效果的界面添加如下代碼
<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>
除此之外的JS直接放在一個(gè)Js文件里,引用進(jìn)來(lái)就行了
下拉列表是怎么加載的呢?看下面的一個(gè)方法就知道了
加載列表
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條,大家可以根據(jù)自己的情況進(jìn)行調(diào)整
$.cookie("site", stringcookie, { expires: 7 });
break;
} else {//如果超出10個(gè)的話就取最后10個(gè)
stringcookie = textval + "|" + stringcookie;
}
}
}
} else {
html += "<li>沒(méi)有記錄</li>"
}
getid("allSitesBoxContent").innerHTML = html;
}
完成了這些之后我們只需要在單擊查詢時(shí)進(jìn)行存儲(chǔ)Cookie就行了,看下面的方法
操作Cookie類(lèi)
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);
}
調(diào)用 時(shí)這樣寫(xiě)
好了功能完成。
進(jìn)行具體的測(cè)試
代碼寫(xiě)的不是很好,希望大家多提提建議,我們進(jìn)行相應(yīng)修改爭(zhēng)取更完善。
Cookie是存儲(chǔ)的客戶端的,一個(gè)并且只能訪問(wèn)同域名下的Cookie,子域名之間可以相互訪問(wèn),只要加上domain屬性就行了,存儲(chǔ)的方法如下
取的時(shí)間直接寫(xiě) $.cookie("domain");就好了,只要是子域名,都這樣調(diào)用,這樣可以達(dá)到本域名下的Cookie共享的功能。
Cookie的有效利用會(huì)給我們的網(wǎng)站帶來(lái)N多意想不到的效果和功能,大家交流下
更多關(guān)于jQuery操作cookie相關(guān)內(nèi)容可查看本站專(zhuān)題:《jQuery的cookie操作技巧總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
- jQuery的Cookie封裝,與PHP交互的簡(jiǎn)單實(shí)現(xiàn)
- jquery.cookie() 方法的使用(讀取、寫(xiě)入、刪除)
- jquery.cookie用法詳細(xì)解析
- 使用jQuery操作Cookies的實(shí)現(xiàn)代碼
- jQuery操作cookie方法實(shí)例教程
- jquery.cookie.js 操作cookie實(shí)現(xiàn)記住密碼功能的實(shí)現(xiàn)代碼
- 基于JQuery的cookie插件
- jquery.cookie.js使用指南
- jquery.cookie.js的介紹與使用方法
- jQuery cookie的公共方法封裝和使用示例
相關(guān)文章
jQuery實(shí)現(xiàn)簡(jiǎn)單的輪播圖效果
這篇文章主要為大家詳細(xì)介紹了jQuery實(shí)現(xiàn)簡(jiǎn)單的輪播圖效果,實(shí)現(xiàn)自動(dòng)播放,能手動(dòng)切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
jQuery開(kāi)發(fā)仿QQ版音樂(lè)播放器
這篇文章主要介紹了jQuery開(kāi)發(fā)仿QQ版的音樂(lè)播放器,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07
jQuery僅用3行代碼實(shí)現(xiàn)的顯示與隱藏功能完整實(shí)例
這篇文章主要介紹了jQuery僅用3行代碼實(shí)現(xiàn)的顯示與隱藏功能,以完整實(shí)例形式分析了jQuery實(shí)現(xiàn)鼠標(biāo)響應(yīng)及頁(yè)面元素屬性變換的相關(guān)技巧,需要的朋友可以參考下2015-10-10
使用veloticy-ui生成文字動(dòng)畫(huà)效果
這篇文章主要介紹了使用veloticy-ui生成文字動(dòng)畫(huà)效果及基本使用方法,需要的朋友可以參考下2018-02-02
40個(gè)有創(chuàng)意的jQuery圖片和內(nèi)容滑動(dòng)及彈出插件收藏集之二
在網(wǎng)頁(yè)的首頁(yè)或圖片專(zhuān)題頁(yè)面很多地方都會(huì)用到圖片滑動(dòng)插件來(lái)循環(huán)切換多張圖片,并且用戶可以點(diǎn)擊左右按鈕來(lái)切換圖片。2011-12-12
自己用jQuery寫(xiě)了一個(gè)圖片的馬賽克消失效果
這篇文章主要介紹的是自己用jQuery寫(xiě)了一個(gè)圖片的馬賽克消失效果實(shí)現(xiàn)過(guò)程,需要的朋友可以參考下2014-05-05
JQuery標(biāo)簽頁(yè)效果的兩個(gè)實(shí)例講解(4)
本文跟大家分享了兩個(gè)Jquery標(biāo)簽頁(yè)效果,各有各的特色,希望大家都會(huì)喜歡,并且能夠熟練掌握,感興趣的小伙伴們可以參考一下2015-09-09
新聞上下滾動(dòng)jquery 超簡(jiǎn)潔(必看篇)
下面小編就為大家?guī)?lái)一篇新聞上下滾動(dòng)jquery 超簡(jiǎn)潔(必看篇)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01

