当我清除并将其他商品添加到购物车时,我清除的商品又来了

时间:2019-03-24 03:41:23

标签: javascript jquery html

这是我用于购物车的代码。使用此代码时,问题是当我单击清除按钮,然后添加另一个项目时,我清除的前一个项目又回来了

我已经尝试过saveCart函数,以使其能够正常工作,但解决该问题仍然没有进展

这是购买物品的按钮(我只显示按钮,因为可能只在这里显示效果)

<input type="button" name="" value="B U Y" class="buyBut add-to-cart" data-name="Avocado & Brownie Cake" data-price="150000">

<input type="button" name="" value="B U Y" class="buyBut add-to-cart" data-name="Strawberry & Watermelon Cake" data-price="65000">

这是显示项目和清除按钮的空间

<table id="show-cart">
 <br>
</table>
 <br>
<button id="clear-cart" onClick="clearCart()">Clear Cart</button>

这是JQuery(我使用JQuery 3.3.1.min)

$(".add-to-cart").click(function(event){
 event.preventDefault();
 var name = $(this).attr("data-name");
 var price = Number($(this).attr("data-price"));
 addItemToCart(name, price, 1);
 displayCart();
 });

function displayCart(){
 var cartArray = listCart();
 var output ="";
 for (var i in cartArray){
   output +=
 "<tr>"
 +"<td class='itemName'>"
 +cartArray[i].name
 +"</td>"
 +"<td class='itemPrice'>"
 +"Rp "
 +cartArray[i].price
 +"</td>"
 +"<td>"
 +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
 +"</td>"
 +"<td class='itemCount'>"
 +cartArray[i].count
 +"</td>"
 +"<td style='width:20px;'>"
 +"</td>"
 +"<td>"
 +"<span class='sub-item' data-name='"+cartArray[i].name+"'>-</span>"
 +"</td>"
 +"<td style='width:12px;'>"
 +"</td>"
 +"<td>"
 +"<span class='delete-item' data-name='"+cartArray[i].name+"'>&times;</span>"
 +"</td>"
 +"</tr>"
  }

 $("#show-cart").html(output);
 $("#total-cart").html( totalCart() );
 $("#cart-count").html( countCart() );
 saveCart();
}

$("#show-cart").on("click", ".delete-item", function(event) {
 var name = $(this).attr("data-name");
 removeItemFromCartAll(name);
 displayCart();
});

$("#show-cart").on("click", ".sub-item", function(event) {
 var name = $(this).attr("data-name");
 removeItemFromCart(name);
 displayCart();
});

这是Javascript

 var cart = [];

 var Item = function(name, price, count){
     this.name = name;
     this.price = price;
     this.count = count;
 }

 // adding item to cart
 function addItemToCart(name, price, count) {
     for (var i in cart) {
       if (cart[i].name === name ) {
         cart[i].count += count;
         return;
       }
     }
     var item = new Item(name, price, count);
     cart.push(item);
     saveCart();
 }

 // Removes 1 Item From Cart
 function removeItemFromCart(name){
   for (var i in cart) {
     if (cart[i].name === name){
       cart[i].count --;
         if (cart[i].count === 0){
           cart.splice(i, 1)
         }
       break;
     }
   }
   saveCart();
 }

 // Clear 1 Object From Cart
 function removeItemFromCartAll(name){
   for (var i in cart) {
     if (cart[i].name === name){
       cart.splice(i,1);
       break;
     }
   }
   saveCart();
 }

 // Clear The Cart
 function clearCart(){
   cart = [];
   document.getElementById("show-cart").innerHTML = "";
   saveCart();
   document.getElementById("total-cart").innerHTML = "0";
 }

 // Shows Total Count Of Item
 function countCart(){
   var totalCount = 0;
   for (var i in cart){
       totalCount += cart[i].count;
   }
   return totalCount;
 }

 // Shows Total Price
 function totalCart(){
   var totalCost = 0;
   for (var i in cart){
     totalCost += cart[i].price * cart[i].count
   }
   return totalCost;
   saveCart();
 }
 // Returns an array
 function listCart(){
   var cartCopy = [];
   for (var i in cart){
     var item = cart[i];
     var itemCopy = {};
     for (var p in item){
        itemCopy[p] = item[p];
     }
     cartCopy.push(itemCopy);
   }
   return cartCopy;
 }

 function saveCart(){
   localStorage.setItem("shoppingCart", JSON.stringify(cart));
 }

 function loadCart(){
   cart = JSON.parse(localStorage.getItem("shoppingCart"));
 }

loadCart();
displayCart();

我希望得到的输出是,当单击清除按钮时,我添加了一个项目,显示的项目仅为1,而我单击之前购物车中的上一个项目消失了。

1 个答案:

答案 0 :(得分:0)

对不起,我看不懂您的代码,要说的太多了,我想您的错误是由于对表及其元素的寻址管理不善所致。

我修改了我的旧代码之一,使其与您的工作相匹配;这对您来说是一个很大的技术差距,但是我认为这对于您在更好的轨道上进行编程将很有用:)

HTML部分: `

<div id="Bt_BUY">
    <button data-price="150000"  >Avocado & Brownie Cake</button>
    <button data-price="65000"  >Strawberry & Watermelon Cake</button>
</div>

<table id="show-cart">
  <thead>
    <tr>
      <th>name</th>
      <th>price</th>
      <th>count</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

<button id="clear-cart" >Clear Cart</button>

`

JS部分 `

"use strict"

const Buy_obj = {
  List : [],
  DisplayTable : null,

  add( x_name, x_price, x_count ) {

    let idx = this.List.findIndex( e=>e.name=== x_name);

    if (idx>=0)
      { this.List[idx].count += x_count; }
    else
      { this.List.push( { 'name' : x_name, 'price' : x_price, 'count' : x_count } ) }

    this.saveList();
    this.drawTable();
  }
  ,
  clear(){ 
    this.List.length = 0;

    this.saveList();
    this.drawTable();
  }
  ,
  remove( x_name ) {
    let idx = this.List.findIndex( e=>e.name=== x_name);

    if (idx>=0) {
      this.List[idx].count--;
      if (this.List[idx].count <= 0) 
        {  this.List.splice(idx,1) }
    }
    this.saveList();
    this.drawTable();
  }
  ,
  saveList() {
    localStorage.setItem("shoppingCart", JSON.stringify(this.List));
  }
  ,
  loadList() {
    let ls_list = localStorage.getItem("shoppingCart");
    if ( ls_list)
      { this.List = JSON.parse(ls_list); }
  }
  ,
  initialise( $xTable ) {
    this.DisplayTable = $xTable;

    this.loadList();
    this.drawTable();
  }
  ,
  drawTable() {
    this.DisplayTable.innerHTML = "";

    this.List.forEach(e=>{
      let
        T_row  = this.DisplayTable.insertRow(-1),
        T_cell_0 = T_row.insertCell(0),
        T_cell_1 = T_row.insertCell(1),
        T_cell_2 = T_row.insertCell(2);

        T_cell_0.textContent = e.name;
        T_cell_1.textContent = e.price;
        T_cell_2.textContent = e.count;
    })
  }
}

//  *************************** Main *****************************

Buy_obj.initialise ( document.querySelector('#show-cart tbody')  );


document.querySelector('#Bt_BUY').onclick = function(e) {
  if (!e.target.matches('button')) return;
  e.stopPropagation();

  Buy_obj.add( e.target.textContent, e.target.dataset.price, 1 );
}

document.querySelector('#clear-cart').onclick = function(e) {
  Buy_obj.clear();
}

`