首頁  >  文章  >  web前端  >  jquery中cookie用法實例詳解(取得,儲存,刪除等)_jquery

jquery中cookie用法實例詳解(取得,儲存,刪除等)_jquery

WBOY
WBOY原創
2016-05-16 15:21:591518瀏覽

本文實例講述了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("currentMenuID", menuID);

時 未指定域和路徑。

所有當域和路徑不同時會產生不同的cookie

複製程式碼 程式碼如下:
$.cookie("currentMenuID");

$.cookie("currentMenuID");


取值時會產生問題。

故: 複製程式碼
程式碼如下:
$.cookie("currentMenuID", "menuID", { path: "/" });

進行覆蓋。同域下同一個cookieID對應一個值。

下面我們來看個實例
$.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&#63; 
          if (cookie.substring(0, name.length + 1) == (name + '=')) { 
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
            break; 
          } 
        } 
      } 
      return cookieValue; 
    } 
  } 
});

關於cookie的path設定需要注意,如果沒有設定path:'/'的話,path則會根據目錄自動設定[如:http://www.xxx.com/user/,path會設定為' /user']

Jquery操作Cookie記錄使用者查詢資訊

這是一個Cookie資料產生的列表,

每次點擊查詢​​會儲存一個域名,並把最後一次查詢的域名放在最上方。本範例最多儲存10個,大家可以依照自己狀況進行設定

下在咱們一起來看看是怎麼實現的吧
function getid(id) {
return (typeof id == 'string') &#63; 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 &#63; 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 &#63; e.target : e.srcElement;
obj.style.imeMode = 'disabled';
}
function OnPaste(e) {
var obj = e.target &#63; 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 &#63; 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);
}
}

先寫一個操作Cookie的JS檔如下

在這裡面還附帶了這樣一個效果,就是同時輸入多個輸入框的值,如下圖


如果那個輸入框要用這樣的效果只要加一個屬性為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就行了,看下面的方法
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類


呼叫 時這樣寫 複製程式碼
程式碼如下:
setCookie("site", strdomin);

setCookie("site", strdomin);

好了功能完成。

複製程式碼

程式碼如下:

$.cookie("domain", value, { expires: 7, domain: " 7c.com" }); 取的時間直接寫 $.cookie("domain");就好了,只要是子域名,都這樣調用,這樣可以達到本域名下的Cookie共享的功能。

Cookie的有效運用會為我們的網站帶來N多意想不到的效果與功能,大家交流下

更多關於jQuery操作cookie相關內容可查看本站專題:《jQuery的cookie操作技巧總結》 希望本文所述對大家jQuery程式設計有所幫助。
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn