document.cookie = "username=aaa"; document.cookie = "pass=123"; var date = new Date(); date.setSeconds(date.getSeconds() + 10); //設置cookie 及過時時間 //document.cookie = "username=aaa;expires=" + date; 封裝設置cookie方法: function setCookie(cName, cValue, day) { var date = new Date(); date.setDate(date.getDate() + day); document.cookie = cName + '=' + cValue + ';expires=' + date; } setCookie('username', 'aaa', 1); setCookie('pass', '123', 1);
var c = document.cookie; console.log(c); //'username=aaa; pass=123' 封裝獲取cookie的方法: function getCookie(cName) { var cookieObj = {}; var cstring = document.cookie; //'username=aaa; pass=123; city=bbb' --> {username:aaa,pass:123} var ary = cstring.split('; '); //['username=aaa','pass=123'] for (var i = 0; i < ary.length; i++) { var ary1 = ary[i].split('='); cookieObj[ary1[0]] = ary1[1]; } return cookieObj[cName]; } var v = getCookie('pass'); console.log(v);
/* 刪除cookie :原理就是把過時時間設置爲前一天*/ function removeCookie(cName) { setCookie(cName, 1, -1); } removeCookie('username');
參考資料: https://www.cnblogs.com/bq-med/p/8603664.htmlhtml