【问题标题】:Delete cookie in javascript doesn't work [duplicate]在javascript中删除cookie不起作用[重复]
【发布时间】:2015-12-21 18:41:32
【问题描述】:

我用 javascript 用 html 制作了一个小购物车。 您可以使用 cookie 放入物品。 问题是购物车中一行的删除按钮。

function cartShow(){
intTotalItems = 0;
intTotalItems = readCookie("totalItems"); 
tabelrow = "";

for (i = 1; i <= intTotalItems; i++){
    item = "item" + i;
    del = '<a href=""><img src="img/delete.png" onclick="delete1Cookie();" /> </a>';
    thisCookie = "";
    thisCookie = readCookie(item);
    fields = new Array();
    fields = thisCookie.split("|");
    tabelrow += "<tr>"
    + "<td>" + fields[0] + "</td>" 
    + "<td>" + fields[1] + "</td>" 
    + "<td>" + fields[2] + "</td>" 
    + "<td>" + fields[3] + "</td>" 
    + "<td>" + fields[4] + "</td>" 
    + "<td>" + fields[5] + "</td>" 
    + "<td>" + fields[4] * fields[5] + "</td>" 
    + "<td>" + del + "</td>" 
    + "</tr>";
}
document.write(tabelrow); }

function delete1Cookie(){
document.cookie = "item1=; 'empty'; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";}

当我使用我的函数时 readCookie(item1); 我没有问题。它显示了我要删除的产品行。

但是当我只想删除一个 cookie 时,我的整个购物车都变空了。

我的代码设置为一行“item1”只有一个 cookie,因为我认为我尝试了所有方法,所以我首先希望看到它只适用于一个特定的行。

我已经使用了以下代码: https://stackoverflow.com/a/20156194/4912774 它删除了我所有的 cookie:“item1 item2 etc”。

对不起,这是我的第一篇文章,英语不是我的母语

【问题讨论】:

标签: javascript html cookies


【解决方案1】:

删除一个特定的cookie,可以通过设置过去来实现

function deleteCookie(cname) {
    var d = new Date();
    d.setTime(d.getTime() - (24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + "" + "; " + expires;
}

【讨论】:

  • 这是我也用过的代码,还是不行。 function maakCookie(naam, waarde, dagen){ if (dagen){ var datum = new Date(); datum.setTime(datum.getTime()+(dagen*24*60*60*1000)); var verloopdatum = "; expires="+datum.toGMTString(); } else{ var verloopdatum = ""; } document.cookie = naam+"="+waarde+verloopdatum+";path=/"; }
猜你喜欢
  • 2020-08-20
  • 2011-05-08
  • 2014-12-02
  • 2020-03-18
  • 1970-01-01
  • 2013-02-19
  • 2017-12-15
  • 2013-02-06
  • 2012-09-22
相关资源
最近更新 更多