用原生的JS封裝cookie的操作方法
阿新 • • 發佈:2019-01-01
<button onclick="setCookie('username','John',1)">setCookie</button>
<button onclick="getCookie('username')">getCookie</button>
<button onclick="removeCookie('username')">moveCookie</button>
JS:
function setCookie(key, value, t){
var oDate=new Date();
oDate.setDate(oDate.getDate()+t);
document.cookie=key+"="+encodeURIComponent(value)+";expires="+oDate.toUTCString();
if(getCookie(key)){
alert('設定成功');
}else{
alert('設定失敗');
}
}
function getCookie(key){
var str=document.cookie.replace(/;\s*/,';');
var cookieArr=str.split(';');
var cookieObj={};
var len=cookieArr.length;
for(var i=0; i<len; i++){
var item=cookieArr[i];
var k=item.split('=')[0];
var v=item.split('=')[1];
cookieObj[k]=v;
}
if(cookieObj[key]){
return decodeURIComponent(cookieObj[key]);
}else{
return false;
}
}
function removeCookie(key){
document.cookie=key+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
if(!getCookie(key)){
alert('刪除成功');
}else{
alert('刪除失敗');
}
}
console.log(getCookie('username'))