简体   繁体   English

无法从购物车中删除商品(在前端),但在后端可用

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

I have been building a shopping cart in Vanilla JS. 我一直在Vanilla JS中建立购物车。 I have an interface that deals with all the logic in the DOM, with a backend that deals with the manipulation of the array. 我有一个处理DOM中所有逻辑的接口,以及一个处理数组操作的后端。

My problem is that I am having trouble with my button that attempts to remove an items from my cart. 我的问题是我在尝试从购物车中删除商品的按钮遇到麻烦。 Not sure why my code doesn't remove items from the cart, but it definitely works with my tests! 不知道为什么我的代码不会从购物车中删除物品,但是绝对可以在我的测试中使用!

I have tried to link the items in the cart to an id which increments as you had more to the cart (so each item in the cart has it's own unique id) and I've been trying to access these individually via an addEventLister('click'), then call my removeItem() method and then render the cart outside of the loop. 我试图将购物车中的商品链接到一个ID,该ID会随着您对购物车的增加而增加(因此购物车中的每个商品都有其自己的唯一ID),并且我一直尝试通过addEventLister('单击”),然后调用我的removeItem()方法,然后在循环外部渲染购物车。 It doesn't work unfortunately and I'm quite stuck. 不幸的是,它无法正常工作,我感到非常困惑。 flow of data cart.js > interface > index.html 数据流cart.js>接口> index.html

cart.js 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 - deals with all DOM components 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 的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>

Well, there are a lot of issues with this code. 好吧,这段代码有很多问题。 First, you're probably repeating some ids on some elements. 首先,您可能在某些元素上重复了一些id。 Every id needs to be unique, otherwise you won't be able to get elements using getElementById . 每个id都必须是唯一的,否则您将无法使用getElementById获取元素。 It is common practice to prepend the value of the id with a keyword that means what exactly the element is. 通常的做法是在id的值前加上一个关键字,该关键字表示元素的确切含义。

Second, the remove button elements are not rendered yet when you run the removeItemButtonFunctionality at the end of the initialize function. 其次,当您在initialize函数的末尾运行removeItemButtonFunctionality时,尚未呈现remove按钮元素。 Those event handlers need to be added dynamically as you add the items. 这些事件处理程序需要在添加项目时动态添加。

Third, it's not an issue, but I would probably change the code so that when renderCart is called, the cart is rendered, instead of returning a string and expecting that the other function will do that for you. 第三,这不是问题,但是我可能会更改代码,以便在renderCart时,呈现购物车,而不是返回字符串并期望其他函数会为您完成此操作。 For example, on the removeItemButtonFunctionality you're not doing anything when calling rederCart() . 例如,在removeItemButtonFunctionality上,调用rederCart()时不执行任何操作。

The same would apply to the renderTotal . 这同样适用于renderTotal

So, in the end, I would change the code to be like this: 因此,最后,我将代码更改如下:

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();
    });
  })
}

and renderTotal : renderTotal

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

addToButtonFunctionality would only call the render functions: addToButtonFunctionality将仅调用渲染函数:

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

and at the end of the function you would only need to call: 在该函数的结尾,您只需调用:

showItems()
addToButtonFunctionality()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM