Cookie概念
Cookie 用于存储页面的用户信息
常见例子:自动登录、记住用户名或密码
Cookie
特性
同一个网站中所有页面共享一套Cookie
(域名和端口一致,就算路径不一样,也能共享一套Cookie)
和localStorage/sessionStorage的区别是,Cookie所占有的数量有限,存储东西比较少,浏览器一般只要存放300个Cookie,每个站点最多存放20个Cookie,大小限制为4KB
数量、大小有限
过期时间
使用JavaScript操作Cookie
创建Cookie
document.cookie=”名字=值 ”
document.cookie="user=family";
document.cookie="pass=123456";
alert(document.cookie);
注意
JS
“
=
”代表覆盖,
cookie
“
=
”代表添加
使用JavaScript操作Cookie
删除
Cookie
过期时间:expires=时间
var oDate=new Date();
oDate.setDate(oDate.getDate()+8);在此处+就是设置什么时候过期,如果要删除就变成-1.
alert(oDate.getFullYear()+'-'+(oDate.getMonth()+1)+'-'+oDate.getDate());
document.cookie="user=family;expires="+oDate;
封装
Cookie
封装三个函数
setCookie()——创建Cookie
getCookie()——获取Cookie
removeCookie()——删除Cookie
练习1:
封装Cookie
使用函数封装,达到能够创建Cookie、读取Cookie以及删除Cookie的要求
function
setCookie
(
name
,
value
,
iDay
){
//分别代表cookie名称、cookie值、存储时间
//首先将cookie的格式拼出来
//document.cookie="name=value;expires=date";
//然后name就换为name,vlaue就换为value,至于date就要算出这个日期对象
var
oDate
=
new
Date
();
oDate
.
setDate
(
oDate
.
getDate
()+
iDay
);
除了天我们还可以设置,时分秒等时间,但是删除日期除了天其他就不行
document
.
cookie
=
name
+
'='
+
value
+
';expires='
+
oDate
;
}
//a=12; b=5; c=8; d=99
function
getCookie
(
name
){
//1、先给cookie做一下字符串分割,
var
arr
=
document
.
cookie
.
split
(
"; "
);
//分割后变为数组,a=12 b=5 c=8 d=99
//2、循环数组
for
(
var
i
=
0
;
i
<
arr
.
length
;
i
++){
var
arr2
=
arr
[
i
].
split
(
"="
);
//根据“=”再次分割
//arr2[0]——》存储的名称 abcd
//arr2[1]——》存储的值 12 5 8 99
if
(
arr2
[
0
]==
name
){
//代表找到我想要的东西了
return
arr2
[
1
];
}
}
//另一种可能,用户第一次来网站,还没有cookie,所以肯定什么也找不到。所以在循环一次后就直接return 一个字符串,告诉用户什么也没找到。
}
function
removeCookie
(
name
){
//name名称,再随便来个值1,后面的才是重点-1,时间过期了,所以就成为了负值
setCookie
(
name
,
1
,-
1
);
}
//setCookie('uesrName','huyangliuyi',365);
//setCookie('password','987654',30);
//试试看有没有读取到cookie
//alert(getCookie('uesrName'));
//删除cookie
removeCookie
(
'uesrName'
);
//先看看里面有哪些数据
alert
(
document
.
cookie
);
练习题:增加 获取 删除cookie,并且使用封装函数
<button class="but1">增加</button>
<br>
<button class="but2">获取</button>
<h1></h1>
<button class="but3"> 删除</button>
<script>
var but1 = document.querySelector(".but1")
var but2 = document.querySelector(".but2")
var but3 = document.querySelector(".but3")
var h1 = document.querySelector("h1")
but1.onclick = function () {
var namen = prompt("输入cookie名称");
var values = prompt("输入cookie的值")
setCookie(namen, values, 1)
}
but2.onclick = function () {
var str = prompt("输入cookie名称")
var arr = getCookie(str);
h1.innerHTML = str + "的值是:" + arr;
}
but3.onclick = function () {
var namen = prompt("请输入要删除的cookie名称");
removeCookie(namen);
}
function removeCookie(namen) {
setCookie(namen, 1, -1);
}
function setCookie(namens, value, time) {
var oDate = new Date();
oDate.setDate(oDate.getDate() + time);
document.cookie = namens + "=" + value + ";expires=" + oDate;
}
function getCookie(name) {
var arr = document.cookie.split("; ");
for (var i = 0; i < arr.length; i++) {
var arr2 = arr[i].split("=");
if (arr2[0] == name) {
return arr2[1];
}
}
return "";
}
</script>