【问题标题】:how to add multiple items to an object in javascript如何在javascript中将多个项目添加到一个对象
【发布时间】:2018-11-16 02:11:52
【问题描述】:

我正在编写一个 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'];
  }
}

【问题讨论】:

标签: javascript


【解决方案1】:

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

按照下面的方法,让我知道它是否适合你。

<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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-06
    • 2017-01-19
    • 2019-11-25
    • 2021-07-14
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多