cookie的封裝和刪除修改
阿新 • • 發佈:2018-11-21
空格 如果 getc += spl dddd lse options 分離 一、設置
name = value;
path = 路徑;
expires = new Date();
var d = new Date();
d.setDate(30)
document.cookie = "password = tp;path = /;expires = "+d
var d2 = new Date();
d2.setDate(30)
document.cookie = "password = 123456;path = /; expires = " +d
封裝
name value 一定會改;
path expires 不一定會改
分離
function setCookie (name , value,path, expires){
//根據參數判斷是否拼接path 和expires;
var str = name + "="+value;
if(path){
str += "; path=" + path;
}
if(expires){
var d = new Date();
d.setDate(d.getDate() + expires)
str += ";expires = " +d;
}
console.log(str);
document.cookie = str;
}
字符串拼接的封裝
setCookie ("sss","hhhh","/cookie",20)
如果不定參(非必選參數)有多個,我們一般會把這樣的參數放進一個對象之中
function setCookie (name,value,options){
//根據參數判定是否拼接path和expires;
var str = name + "=" + value;
if(options.path){
str += ";path =" + options.path;
}
if(option.expires) {
var d = new Date();
d.setDate(d.getDate() + options.expires)
str += ";expires = " +d;
}
console.log(str);
document.cookie = str;
}
setCookie ("hhh","dddd",{
expires:30
})
優雅封裝
function setCookie (name,value,options){
document.cookie = (function(name,value,options){
var str = name + "="+value;
if(options.path){
str += ";path +" = "options.path
}
if(options.expires){
var d = new Date();
d.setDate(d.getDate()+options.expires)
str += ";expires =" +d;
}
return str;
}) (name,value,options)
}
setCookie ("hhh","dddd",{
expires:30
})
刪除
function removeCookie (name,path){
setCookie(name,"",{
expires : -1,
path : path
})
}
removeCookie ("hhhh")
獲取
function setCookie (name,value,options){
docunment.cookie = (function(name,value,options){
var str = name + "=" + value;
if(options.path){
str += ";path = " + options.path;
}
if(options.expires){
var d = new Date();
d.setDate(d.getDate() + options.expires)
str += ";expires = " + d;
}
return str;
})(name,value,options)
}
setCookie ("username","tp",{
expions:10
})
setCookie ("password" ,"123456",{
expires :1 0
})
1、每條cookie 以 ; 空格進行分割;
2、key 和 value 以 = 進行分割;
function getCookie (key){
var str = document.cookie ;
//字符串轉化成數組
// string.split() ; 切割字符串;
var arr = str.split(";")
//console.log(str,arr);
//var res = arr.map(function(item,index){
// if(key == item.split("=")[0]){
// return (item.split("=")[1]);
}
return false
})
for(var i = 0; i < arr.length; i ++){
if(key === arr[i].split("=")[0]){
return arr[i].split("=")[1];
}
}
console.og(res)
return "";
}
console.log(getCookie ("username"));
cookie的封裝和刪除修改