原生js学习笔记7——本地存储之cookie操作
什么是cookie
• 用来保存页面信息的,如用户名、密码
• cookie的特性:同一个网站中所有的页面共享一套cookie;数量、大小限制;过期时间
• js中使用cookie:document.cookie
如何设置cookie?
在js中,使用document.cookie = "键=值"即可,但是这种方式设置的cookie由于没有添加过期时间,所以关闭浏览器,cookie就丢失,我们要在后边继续加上expires=时间设置上过期时间即可.
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
// 获取系统当前时间
var oDate = new Date();
// 设置距离当前时间多少天后cookit过期
oDate.setDate(oDate.getDate() + 30);
// 设置cookie及过期时间
document.cookie = "userName=hello;expires=" + oDate;
document.cookie = "password=123456;expires=" + oDate;
alert(document.cookie);
</script></head><body>
</body></html>
效果图:
cookie
如何从cookie中取值
示例:将用户名密码写入
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div {
width: 500px;
height: 500px;
margin: 0 auto;
}
#userName {
display: block;
width: 200px;
height: 30px;
margin: 0 auto;
}
#password {
display: block;
width: 200px;
height: 30px;
margin: 0 auto;
}
#save {
display: block;
width: 100px;
height: 20px;
margin: 0 auto;
}
#cokie {
display: block;
width: 100px;
height: 20px;
margin: 0 auto;
}
</style>
<script type="text/javascript">
window.onload = function () {
var oBtn = document.getElementById('save');
var oBtn1 = document.getElementById('cokie');
var name ;
var pass ;
oBtn.onclick = function () {
name = document.getElementById('userName').value;
pass = document.getElementById('password').value;
var oDate = new Date();
oDate.setDate(oDate.getDate() + 30);
// 写入cookie
document.cookie = "userName=" + name + "; expires=" + oDate;
document.cookie = "password=" + pass + "; expires=" + oDate;
}
oBtn1.onclick = function () {
var oCookie = document.cookie.split('; ');
for (var i = 0; i < oCookie.length; i++) {
var temp = oCookie[i].split('=');
if (i == 1) {
document.getElementById('userName').value = temp[1];
};
if (i == 0) {
document.getElementById('password').value = temp[1];
};
};
}
}
</script></head><body>
<div>
<input type = "text" id = "userName" placeholder = "用户名"> <br>
<input type="text" id = "password" placeholder = "密码"> <br>
<input type="button" value = "保存" id = "save">
<input type="button" value = "从cookie读取" id = "cokie">
</div>
</body></html>