分享javascript中方便增刪改cookie的一個類

來源:互聯網
上載者:User

在學校失業一個半月了,還沒找到實習,悲劇,蛋疼,把jquery.cookie.js改了一下,改成了純javascript版本,以備我以後項目只需,增加了一個得到頁面全部cookie索引值的功能。

主要是通過對document.cookie字串的分析來進行功能的組裝的。

溫習一下javascript中對cookie的操作:

增加cookie可以用document.cookie="userId=111";來實現

完整版可以用:document.cookie="userId=111;domain=.google.com;path=\;secure=secure;expire="+date.toGMTString();

可以設定cookie的到期時間,網域名稱,路徑

需要刪除只要將expire的時間設為現在之前就可以了

現在上我修改的javascript.cookie.js的類

View Code

/*cookie helper classeasy to write,get,delete */var myCookie={    get:function(name){        if(typeof name != "undefined")        {            //if name given call the get value function            return myCookie_get(name);        }else{            //if name is not given,i want get all the cookie item            return myCookie_getAll();        }    },    add:function(name,value,options){        //write the cookie        myCookie_add(name,value,options);    },    delete:function(name){        //delete the cookie        myCookie_add(name,null);    }}String.prototype.Trim = function(){    return this.replace(/^\s+/g,"").replace(/\s+$/g,"");}/*cookie write function@name:the cookie name not null@value:the cookie value null==delete the cookie@option:{"expires":expire time;"path":/;"domain":localhost;"secure":secure} */function myCookie_add(name,value,options){    if (typeof value != 'undefined') { // name and value given, set cookie        options = options || {};        if (value === null) {            value = '';            options.expires = -1;        }        var expires = '';        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {            var date;            if (typeof options.expires == 'number') {                date = new Date();                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));            } else {                date = options.expires;            }            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE        }        var path = options.path ? '; path=' + options.path : '';        var domain = options.domain ? '; domain=' + options.domain : '';        var secure = options.secure ? '; secure' : '';        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');    }}/*get the name cookie@name:the cookie's name */function myCookie_get(name){    var cookieValue = null;    if (document.cookie && document.cookie != '') {        var cookies = document.cookie.split(';');        for (var i = 0; i < cookies.length; i++) {            var cookie = cookies[i].Trim();            // Does this cookie string begin with the name we want?            if (cookie.substring(0, name.length + 1) == (name + '=')) {                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));                break;            }        }    }    return cookieValue;}/*get all the cookie return as a json */function myCookie_getAll(){    var cookieArray = new Array();    var str="";    var temp;    if (document.cookie && document.cookie != '') {        var cookies = document.cookie.split(';');        for (var i = 0; i < cookies.length; i++) {            var cookie = cookies[i].Trim();            temp=cookie.split('=');            //take the            cookieArray.push("{\"name\":\""+decodeURIComponent(temp[0])+"\",\"value\":\""+decodeURIComponent(temp[1])+"\"}");        }        str=cookieArray.join(",");    }    str="["+str+"]";    return eval('('+str+')');}

調用也是相當簡單

View Code

myCookie.add("useraccount","admin",{"expires":5});//加入一個期限為5天的cookie            alert(myCookie.get("useraccount"));//取出cookie            cookies=myCookie.get();//得到所有的cookie            for(var i=0;i<cookies.length;i++)            {                alert(cookies[i]["name"]+":"+cookies[i]["value"]);            }            myCookie.delete("useraccount");//刪除剛剛添加的cookie            alert(myCookie.get("useraccount"));

希望大家指導指點

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.