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

这篇文章主要介绍了jquery中cookie用法,结合实例详细分析了jQuery操作cookie的获取,存储,删除等操作,并附带了Jquery操作Cookie记录用户查询过信息实现方法,需要的朋友可以参考下
 

本文实例讲述了jquery中cookie用法。分享给大家供大家参考,具体如下:

cookie在jquery中有指定的cookie操作类,下面我先来介绍我们在使用cookie操作类时的一些问题,然后介绍正确的使用方法。

使用JQuery操作cookie时 发生取的值不正确的问题:
结果发现cookie有四个不同的属性:
名称,内容,域,路径

?
1
2
3
4
$.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']

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
$.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文件如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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' );
});
//取出Cookie
var icpSite = $.cookie( "site" );
if (icpSite) {
//取出Cookie不为空的话就给当前框
icpSite = icpSite.split( '|' )[0];
$( "#site" ).val(icpSite);
}
}

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

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

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

?
1
2
3
4
5
6
7
8
<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文件里,引用进来就行了
下拉列表是怎么加载的呢?看下面的一个方法就知道了

加载列表

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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程序设计有所帮助。

转载于:https://www.cnblogs.com/lhlong/p/5946406.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值