删除Cookie

时间:2011-07-31 02:20:04

标签: javascript jquery cookies

我正在为我的网站创建一个包含Cookie的添加[ITEM]功能。 现在Add [ITEM]部分可以工作,但我需要删除[ITEM]。 这是我的代码:

$(window).load(function(){
   function getCookie(c_name){
 var i,x,y,ARRcookies=document.cookie.split(";");
 for (i=0;i<ARRcookies.length;i++){
   x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
   y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
   x=x.replace(/^\s+|\s+$/g,"");
   if (x==c_name){
     return unescape(y);
     }}}
 function setCookie(c_name,value,exdays){
 var exdate=new Date();
 exdate.setDate(exdate.getDate() + exdays);
 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
 document.cookie=c_name + "=" + c_value;
 }
     $(document).ready(function(){
var cookieyess=getCookie("save");
 if(cookieyess!==undefined&&cookieyess!==null&&cookieyess!==""){
$('#save1').show();
    }
    else{
 $('#save1').hide();
   }
 }); 
  $('#save_1').click(function(){
 var cookieyes=getCookie("save");
 if(cookieyes!==undefined&&cookieyes!==null&&cookieyes!==""){
$('#save1').show();
    }
    else{
 $('#save1').show();
        setCookie("save","yes",365);
    }
  });
});

现在我需要创建一个函数,所以当你单击Removes时它会删除那个Cookie。

2 个答案:

答案 0 :(得分:2)

要删除mycookie,这应该可以通过设置过去的过期日期来实现:

setCookie("mycookie", "", -1)

答案 1 :(得分:1)

这是我写的一个小型图书馆:

var myCookieHandler = (function () {
    return {
        createCookie: function (name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        readCookie: function (name) {
            var nameEq = name + "=";
            var ca = document.cookie.split(';');
            var i;

            for (i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
                if (c.indexOf(nameEq) === 0) { return c.substring(nameEq.length, c.length); }
            }

            return null;
        },
        deleteCookie: function (name) {
            this.createCookie(name, null, -1);
        }
    };
}());

用法:

myCookieHandler .writeCookie("Login","true",2);

var cookieValue=myCookieHandler.readCookie("Login");

myCookieHandler.deleteCookie("Login");

希望这会有所帮助..