javascript cookies不会被删除

时间:2014-07-18 08:22:36

标签: javascript cookies

我写了一个小的javascript函数

 function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
function deleteCookie(key)
{
  // Delete a cookie by setting the date of expiry to yesterday
  date = new Date();
  date.setDate(date.getDate() -1);
  document.cookie = escape(key) + '=;expires=' + date;
}

在我的控制台中.i通过document.cookie =&#34;设置一个cookie;下一个= true&#34 ;; 我打电话给getCookie(&#39; Next&#39;)。返回true 我打电话给deleteCookie(&#39; Next&#39;)然后调用getCookie(&#39; Next&#39;)仍然返回true.can任何人请告诉为什么它不删除cookie ??

3 个答案:

答案 0 :(得分:2)

试试这个:

function deleteCookie(key) {
  document.cookie = 
    encodeURIComponent(key) +
    "=deleted; expires=" +
    new Date(0).toUTCString();
}

答案 1 :(得分:1)

使用JQuery删除cookie

//To set a cookie
02
$.cookie('the_cookie', 'the_value');
03

04
//Create expiring cookie, 7 days from then:
05
$.cookie('the_cookie', 'the_value', { expires: 7 });
06

07
//Create expiring cookie, valid across entire page:
08
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
09

10
//Read cookie
11
$.cookie('the_cookie'); // => 'the_value'
12
$.cookie('not_existing'); // => null
13

14
//Delete cookie by passing null as value:
15
$.cookie('the_cookie', null);
16

17
// Creating cookie with all availabl options
18
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com',
19
         secure: true, raw: true });

答案 2 :(得分:0)

也设置cookie的域对我有用:

document.cookie = 'cookiename=; Max-Age=0; path=/; domain=.example.com';