我有一个模拟网上商店,我正在为一个项目制作,但我似乎无法让我的空购物车按钮工作。用户单击添加或删除项目以在购物车中添加或删除项目,但清空购物车的按钮不起作用。
<button type="button" onclick="removeAll()" style="color:black">Empty Cart</button>
我试过通过单击按钮单独删除每个项目,但它只删除了数组中的第一个项目。
function removeItem(itemIndex) { //remove item from cart
cart.remove(itemIndex);
cart.display();
}
function removeAll(itemIndex) { //removes all items from cart
removeItem(0);
removeItem(1);
removeItem(2);
}
function Cart (holder, items) {
this.holder = holder;
this.items = items;
this.quantities = Array();
for (var i=0; i<items.length; i++)
this.quantities[i] = 0;
this.add = function (index) {
this.quantities[index]++;
}
this.remove = function (index) {
if (this.quantities[index] > 0)
this.quantities[index]--;
}
任何帮助将不胜感激,谢谢
最佳答案
查看该代码,您希望 removeAll
为:
function removeAll() { //removes all items from cart
var n;
for (n = 0; n < cart.quantities.length; ++n) {
cart.quantities[n] = 0;
}
cart.display();
}
...虽然将 removeAll
放在 Cart.prototype
上可能有意义(相应地调整)。
关于javascript - 如何从数组中删除所有项目并显示它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593417/