1. 程式人生 > >js 操作cookie,getCookie,setCookie ,removeCookie

js 操作cookie,getCookie,setCookie ,removeCookie

span repl console etc 空格 alert true nbsp name

 document.cookie = ‘name=‘+‘username‘;
    document.cookie = ‘value=‘+‘value1‘;

    var cookarr = document.cookie.replace(/\s/g,"").split(‘;‘);//將cookie的空格全部替換掉,不然會出現空格,使結果無法判斷
    var havcome = false;
    for (var i=0;i<cookarr.length;i++){
        var str = cookarr[i].split(‘=‘);
        if(str[0]==‘dateam‘) {
            havcome 
= true; break } } console.log(document.cookie); console.log(havcome); var date = new Date(); var day = date.getTime(); console.log(day); var newday = new Date(day + 7*24*60*60*1000);//設置過期時間,這裏設置為七天之後; var oldday = new Date(day -1);//設置刪除時間,只要過期時間在設置時間之前,就可以將cookie刪除;
console.log(newday.toUTCString()); if (!havcome){ document.cookie = ‘dateam‘+‘=‘+‘haha‘+‘;expires=‘+newday.toUTCString(); alert(‘歡迎你第一次來‘); } document.cookie = ‘dateam‘+‘=‘+‘haha‘+‘;expires=‘+oldday.toUTCString();//將過期時間設置為已經過去的 1 ms,則可以立即刪除dateamcookie

js 操作cookie,getCookie,setCookie ,removeCookie