jquery中cookie用法實例詳解(獲取,存儲,刪除等)
本文實例講述了jquery中cookie用法。分享給大家供大家參考,具體如下:
cookie在jquery中有指定的cookie操作類,下面我先來介紹我們在使用cookie操作類時的一些問題,然后介紹正確的使用方法。
使用JQuery操作cookie時 發(fā)生取的值不正確的問題:
結(jié)果發(fā)現(xiàn)cookie有四個不同的屬性:
名稱,內(nèi)容,域,路徑
$.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
使用:
時 未指定域和路徑。
所有當域和路徑不同時會產(chǎn)生不同的cookie
取值時會產(chǎn)生問題。
故:
進行覆蓋。同域下同一個cookieID對應(yīng)一個值。
下面我們來看個實例
關(guān)于cookie的path設(shè)置需要注意,如果不設(shè)置path:'/'的話,path則會根據(jù)目錄自動設(shè)置[如:http://www.xxx.com/user/,path會被設(shè)置為 '/user']
$.extend({
/**
1. 設(shè)置cookie的值,把name變量的值設(shè)為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操作Cookie記錄用戶查詢過信息

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

如果那個輸入框要使用這樣的效果只要添加一個屬性為url="true"就行了,這樣方便 可操作性強,想給那個框加效果就加上這個屬性,不想加的直接不加url="true"
就OK了。
在使用這個效果的界面添加如下代碼
<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直接放在一個Js文件里,引用進來就行了
下拉列表是怎么加載的呢?看下面的一個方法就知道了
加載列表
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ù)自己的情況進行調(diào)整
$.cookie("site", stringcookie, { expires: 7 });
break;
} else {//如果超出10個的話就取最后10個
stringcookie = textval + "|" + stringcookie;
}
}
}
} else {
html += "<li>沒有記錄</li>"
}
getid("allSitesBoxContent").innerHTML = html;
}
完成了這些之后我們只需要在單擊查詢時進行存儲Cookie就行了,看下面的方法
操作Cookie類
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)用 時這樣寫
好了功能完成。
進行具體的測試
代碼寫的不是很好,希望大家多提提建議,我們進行相應(yīng)修改爭取更完善。
Cookie是存儲的客戶端的,一個并且只能訪問同域名下的Cookie,子域名之間可以相互訪問,只要加上domain屬性就行了,存儲的方法如下
取的時間直接寫 $.cookie("domain");就好了,只要是子域名,都這樣調(diào)用,這樣可以達到本域名下的Cookie共享的功能。
Cookie的有效利用會給我們的網(wǎng)站帶來N多意想不到的效果和功能,大家交流下
更多關(guān)于jQuery操作cookie相關(guān)內(nèi)容可查看本站專題:《jQuery的cookie操作技巧總結(jié)》
希望本文所述對大家jQuery程序設(shè)計有所幫助。
相關(guān)文章
jQuery圖片旋轉(zhuǎn)插件jQueryRotate.js用法實例(附demo下載)
這篇文章主要介紹了jQuery圖片旋轉(zhuǎn)插件jQueryRotate.js用法,結(jié)合實例形式分析了圖片旋轉(zhuǎn)插件jQueryRotate.js用法,并附帶了demo示例代碼供讀者下載,需要的朋友可以參考下2016-01-01
jQuery使用cookie與json簡單實現(xiàn)購物車功能
這篇文章主要介紹了jQuery使用cookie與json簡單實現(xiàn)購物車功能的方法,介紹了jQuery實現(xiàn)購物車的步驟與關(guān)鍵代碼,需要的朋友可以參考下2016-04-04
jQuery實現(xiàn)的給圖片點贊+1動畫效果(附在線演示及demo源碼下載)
這篇文章主要介紹了jQuery實現(xiàn)的給圖片點贊+1動畫效果,并附帶在線演示及demo源碼下載,涉及jQuery鼠標事件響應(yīng)及頁面元素屬性動態(tài)操作相關(guān)技巧,需要的朋友可以參考下2015-12-12
jquery 表格分頁等操作實現(xiàn)代碼(pagedown,pageup)
jquery實現(xiàn)支持pagedown,pageup對表格進行操作的實現(xiàn)代碼,需要的朋友可以參考下。2010-04-04
JQuery UI DatePicker中z-index默認為1的解決辦法
用到JQuery UI的DatePicker時,發(fā)現(xiàn)如果頁面有其他z-index比較大的控件,datepicker就會被遮住而不能操作。2010-09-09

