javascript - 如何从数组中删除所有项目并显示它?

标签 javascript html

我有一个模拟网上商店,我正在为一个项目制作,但我似乎无法让我的空购物车按钮工作。用户单击添加或删除项目以在购物车中添加或删除项目,但清空购物车的按钮不起作用。

<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/

相关文章:

javascript - 不允许从 Dynamics 365 和本地资源访问本地文件

javascript - 如何仅使用 javascript 获取特定 div/form 的所有子输入?

php - 将 "Selected Users"插入另一个表

html - Flaticon ,定位::before 元素

具有动态宽度的 CSS 和 DIV

javascript - 在正文中加载脚本的顺序并使用 jquery ready

javascript - 使用 JS 访问用户的历史记录

javascript - angularjs中复选框的实现

javascript - 窗口绑定(bind)在 Firefox 中不起作用

javascript - HTML - 将 SELECT 标记内容放入 INPUT type = "text"