簡體   English   中英

無法從購物車中刪除商品(在前端),但在后端可用

[英]Cannot remove items from shopping cart (in the frontend) but works in the backend

我一直在Vanilla JS中建立購物車。 我有一個處理DOM中所有邏輯的接口,以及一個處理數組操作的后端。

我的問題是我在嘗試從購物車中刪除商品的按鈕遇到麻煩。 不知道為什么我的代碼不會從購物車中刪除物品,但是絕對可以在我的測試中使用!

我試圖將購物車中的商品鏈接到一個ID,該ID會隨着您對購物車的增加而增加(因此購物車中的每個商品都有其自己的唯一ID),並且我一直嘗試通過addEventLister('單擊”),然后調用我的removeItem()方法,然后在循環外部渲染購物車。 不幸的是,它無法正常工作,我感到非常困惑。 數據流cart.js>接口> index.html

cart.js

class Cart {
  constructor() {
    this.cartArray = []
    this.total = 0
  }
  add(item) {
    this.cartArray.push(item)
  }
  removeItem(item) {
      var position = this.cartArray.lastIndexOf(item)
      this.cartArray.splice(position, 1)
  }

  calculateTotal() {
    var reducedTotal = this.cartArray.reduce( (previous, current) => {
      return this.total = previous + current.price
    },0)
    return reducedTotal
  }
}

interface.js-處理所有DOM組件

function iniitalize () {
  var itemList = "<table border='1|1'>";
  var shoppingCartList = document.getElementById("shoppingCartList")
  var total = document.getElementById("total")

  var eachParagraph = document.getElementsByClassName('delete-item') 

  var cart = new Cart

  function showItems() {
    for (var i = 0; i < items.length; i++) {
        itemList +="<tr>";
        itemList += "<td>" +  items[i].name + "</td>"
        itemList += "<td>" + items[i].category + "</td>"
        itemList += "<td> " + items[i].price + "</td>"
        itemList += "<td> " + items[i].stock  + "</td>" 
        itemList += ` <td> <button id=${items[i].id}>add to cart</button> </td>`
        itemList +="</tr>";
    }
    itemList += "</table>";
    document.getElementById("itemsList").innerHTML = itemList;
  }

  function renderCart() {
    var print = "";
    var indexOfItem = 0
    cart.cartArray.forEach(function(element, index) {
      print +=  `<p id=${index}  class=${index}>` +  element.name + element.price 
      + `<button id=${indexOfItem}>Remove from cart</button> </p>`
      indexOfItem ++
    })
    return print
  }

  function renderTotal(){
    cart.calculateTotal()
    return "£" + cart.total
  }

  function removeItemButtonFunctionality() {
    cart.cartArray.forEach(function(element, index) {
      shoppingCartList.addEventListener('click', () => {
        cart.removeItem(element)
      })
    })
    renderCart()
  }


  function addToButtonFunctionality() {
    items.forEach( function(element, index) {
      document.getElementById(index).addEventListener('click', () => {
        cart.add(element)
        shoppingCartList.innerHTML = renderCart()
        total.innerHTML = renderTotal()
      })
    })
  }

  showItems()
  addToButtonFunctionality() 
  removeItemButtonFunctionality()
}


window.addEventListener("DOMContentLoaded", iniitalize)

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <h1>Shopping retailer</h1>
</head>
<body>

  <div id="itemsList"></div>
<br>

<h3>Total:</h3>
<div id="total">
</div> 

  <h3>Shopping Cart:</h3>

  <p id="shoppingCartList"></p>





  <script src="src/items.js"></script>
  <script src="src/cart.js"></script>
  <script src="./interface.js"></script>
</body>
</html>

好吧,這段代碼有很多問題。 首先,您可能在某些元素上重復了一些id。 每個id都必須是唯一的,否則您將無法使用getElementById獲取元素。 通常的做法是在id的值前加上一個關鍵字,該關鍵字表示元素的確切含義。

其次,當您在initialize函數的末尾運行removeItemButtonFunctionality時,尚未呈現remove按鈕元素。 這些事件處理程序需要在添加項目時動態添加。

第三,這不是問題,但是我可能會更改代碼,以便在renderCart時,呈現購物車,而不是返回字符串並期望其他函數會為您完成此操作。 例如,在removeItemButtonFunctionality上,調用rederCart()時不執行任何操作。

這同樣適用於renderTotal

因此,最后,我將代碼更改如下:

function renderCart() {
  shoppingCartList.innerHTML = '';
  cart.cartArray.forEach(function(element) {
    shoppingCartList.innerHTML += `<p id="cart${element.id}">${element.name} ${element.price}<button id="remove${element.id}">Remove from cart</button></p>`;
    var removeButton = document.getElementById('remove' + element.id);
    removeButton.addEventListener('click', function() {
      cart.removeItem(element);
      renderCart();
      renderTotal();
    });
  })
}

renderTotal

function renderTotal(){
  total.innerHTML = "£" + cart.calculateTotal();
}

addToButtonFunctionality將僅調用渲染函數:

function addToButtonFunctionality() {
  items.forEach( function(element, index) {
    document.getElementById(index).addEventListener('click', () => {
      cart.add(element)
      renderCart();
      renderTotal();
    })
  })
}

在該函數的結尾,您只需調用:

showItems()
addToButtonFunctionality()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM