【发布时间】: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”。
对不起,这是我的第一篇文章,英语不是我的母语
【问题讨论】:
-
您可以在这里看到一组经过测试的 cookie 实用功能:stackoverflow.com/questions/20156129/…。
-
不要为这些东西使用 cookie。使用web storage。它是supported by all modern browsers,不会使您的 HTTP 请求超出所需的大小,并且与 cookie 不同,它具有合理的 API。
-
顺便说一句,您的代码正在成为The Horror of Implicit Globals 的牺牲品。声明你的变量。
-
最后:发帖前请先搜索。这个问题已经被问了好几次了。
-
@jfriend00 这与我的设置相同。
标签: javascript html cookies