本文實例講述了jquery中cookie用法。分享給大家供大家參考,具體如下:
cookie在jquery中有指定的cookie操作類,下面我先來介紹我們在使用cookie操作類時的一些問題,然后介紹正確的使用方法。
使用JQuery操作cookie時 發生取的值不正確的問題:
結果發現cookie有四個不同的屬性:
名稱,內容,域,路徑
$.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
使用:
所有當域和路徑不同時會產生不同的cookie
故:
下面我們來看個實例
關于cookie的path設置需要注意,如果不設置path:'/'的話,path則會根據目錄自動設置[如:http://www.xxx.com/user/,path會被設置為 '/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操作Cookie記錄用戶查詢過信息
這是一個Cookie數據生成的列表,
每次單擊查詢會存儲一個域名,并把最后一次查詢的域名放在最上方。本例子最多存儲10個,大家可以根據自己情況進行設置
下在咱們一起來看看是怎么實現的吧
先寫一個操作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不執行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');});//取出Cookievar 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條,大家可以根據自己的情況進行調整$.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);}
調用 時這樣寫
進行具體的測試
代碼寫的不是很好,希望大家多提提建議,我們進行相應修改爭取更完善。
Cookie是存儲的客戶端的,一個并且只能訪問同域名下的Cookie,子域名之間可以相互訪問,只要加上domain屬性就行了,存儲的方法如下
Cookie的有效利用會給我們的網站帶來N多意想不到的效果和功能,大家交流下
更多關于jQuery操作cookie相關內容可查看本站專題:《jQuery的cookie操作技巧總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答