<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cookie</title>
</head>
<body>
<script>
window.onload = function() {
// 设置
function setCookie(key, value, day = 15) {
var date = new Date(),
expires = '';
// 设置cookie生存期
date.setTime(date.getTime() + (day * 24 * 60 * 60 * 1000));
expires = date.toUTCString();
document.cookie = key + '=' + value +';expires=' + expires;
}
// 获取
function getCookie(key) {
var key = key + "=", // 存储的cookie字段名
value = ""; // cookie值
if (document.cookie.length > 0) {
// value的位置
var start = document.cookie.indexOf(key),
end = '';
if (start!= -1) {
start += key.length;
end = document.cookie.indexOf(";", start);
if (end == -1)
end = document.cookie.length;
// unescape() 函数可对通过 escape() 编码的字符串进行解码。
value = unescape(document.cookie.substring(start, end))
}
}
console.log(value)
return value;
}
// 调用
setCookie('name', 'sophy', 3)
getCookie('name');
}
</script>
</body>
</html>
网友评论