栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

jquery中cookie用法实例详解(获取,存储,删除等)

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jquery中cookie用法实例详解(获取,存储,删除等)

本文实例讲述了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", "menuID", { path: "/"});
进行覆盖。同域下同一个cookieID对应一个值。

下面我们来看个实例

关于cookie的path设置需要注意,如果不设置path:'/'的话,path则会根据目录自动设置[如:http://www.xxx.com/user/,path会被设置为 '/user']

$.extend({ 

  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 += "
  • " + textval + "

  • "; forlength = forlength + 1; if (forlength > 10) { $.cookie("site", stringcookie, { expires: 7 }); break; } else { stringcookie = textval + "|" + stringcookie; } } } } else { html += "
  • 没有记录
  • " } 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); } }

    在这里面还附带了这样一个效果,就是同时输入多个输入框的值,如下图

    如果那个输入框要使用这样的效果只要添加一个属性为url="true"就行了,这样方便 可操作性强,想给那个框加效果就加上这个属性,不想加的直接不加url="true"
    就OK了。

    在使用这个效果的界面添加如下代码

    
      

    除此之外的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 += "
  • " + textval + "

  • "; forlength = forlength + 1; if (forlength > 10) {//在这里我只加载10条,大家可以根据自己的情况进行调整 $.cookie("site", stringcookie, { expires: 7 }); break; } else {//如果超出10个的话就取最后10个 stringcookie = textval + "|" + stringcookie; } } } } else { html += "
  • 没有记录
  • " } 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);
    }
    
    

    调用 时这样写
    复制代码 代码如下:setcookie("site", strdomin);
    好了功能完成。

    进行具体的测试

    代码写的不是很好,希望大家多提提建议,我们进行相应修改争取更完善。

    cookie是存储的客户端的,一个并且只能访问同域名下的cookie,子域名之间可以相互访问,只要加上domain属性就行了,存储的方法如下
    复制代码 代码如下:$.cookie("domain", value, { expires: 7, domain: "7c.com" });
    取的时间直接写 $.cookie("domain");就好了,只要是子域名,都这样调用,这样可以达到本域名下的cookie共享的功能。

    cookie的有效利用会给我们的网站带来N多意想不到的效果和功能,大家交流下

    更多关于jQuery操作cookie相关内容可查看本站专题:《jQuery的cookie操作技巧总结》

    希望本文所述对大家jQuery程序设计有所帮助。

    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/99004.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号