如何在javascript中向对象添加多个项目

时间:2018-06-06 11:43:47

标签: javascript

我正在写一个ShoppingCart类来添加和删除购物车中的商品 代码用于添加和删除购物车中的商品。

class ShoppingCart{
  constructor(){
    this.total = 0;
    this.items = {};
  }

  addItems(itemName, quantity, price){
    this.itemName = itemName;
    this.quantity = quantity;
    this.price = price;
    this.cost = this.quantity * this.price;

    this.total += this.cost;

    this.items['itemName'] = this.itemName;
    this.items['quantity'] = this.quantity;
  }

  removeItems(itemName, quantity, price){
    this.itemName = itemName;
    this.quantity = quantity;
    this.price = price;
    this.cost = this.quantity * this.price;

    this.total -= this.cost;
    delete this.items['itemName', 'quantity'];
  }
}

1 个答案:

答案 0 :(得分:0)

基本上你需要如何添加和删除列表项。

按照以下方法,让我知道它是否适合您。

<ul id="todo"></ul>
<button onclick="addItemTodo('test')">Add</button>

JS

function addItemTodo(text) {
list = document.getElementById("todo");

item = document.createElement('li');
item.innerText = text;

trash = document.createElement('button');
trash.classList.add('btn1');
trash.addEventListener("click", removeActivity);

icon_trash = document.createElement('i');
icon_trash.classList.add('fas', 'fa-trash-alt', 'fa-2x');
item.appendChild(trash);
trash.appendChild(icon_trash);

list.appendChild(item); }
 function removeActivity() {
var listItems = document.getElementsByTagName("li");
for (var i = 0; i < listItems.length; i++) {
    listItems[i].onclick = function() {
        this.parentNode.removeChild(this);
    }
  }
  }

Live demo