【问题标题】:Cannot substract the total price in shopping cart but I get the correct price when the page is been refreshed无法减去购物车中的总价格,但刷新页面时我得到正确的价格
【发布时间】:2020-10-20 00:50:25
【问题描述】:

我正在构建一个包含两个页面和两个 Javascript 文件的电子商务网站,即:(index.html、cart.html、apps.js 和 cart.js)。单击删除按钮后,如何从购物车 (cart.html) 中减去总价?

这是我的代码:

// cart functionality
table.addEventListener("click", event => {
    if (event.target.classList.contains('fa-close')) {
        let removeItem = event.target;
        console.log('df', removeItem);
        let id = removeItem.dataset.id;
        console.log(id);
        table.removeChild(removeItem.parentElement.parentElement);

        var obj = JSON.parse(localStorage.getItem("cart")) || {}; //fetch cart from storage
      
        var items = obj || []; //get the products
        for (var i = 0; i < items.length; i++) { //loop over the collection
            if (items[i].id === id) { //see if ids match
                items.splice(i, 1); //remove item from array
                break; //exit loop
            }
        }
        localStorage.setItem("cart", JSON.stringify(obj)); //set item back into storage

        //decreasing the cart length
        var cal = JSON.parse(localStorage.getItem('cart'));
        if (cal.length != 0) {
            cart_n.innerHTML = `[${cal.length}]`;
        } else {
            cart_n.innerHTML = '';
        }
          
        //subtractTotal cart
        cal.find(item => {
            tempTotal = 0;
            tempTotal = item.price * item.id
        })
        row.innerHTML = tempTotal;
    }
   
});

【问题讨论】:

  • 似乎是什么问题?您是否在控制台中收到任何错误?当您似乎应该使用.forEach 时,您还使用了.find,您在该循环中的每次迭代中将tempTotal 设置为0,因此新值将只是循环中的最后一个值。您将priceid 相乘,这似乎没有多大意义。
  • 我在控制台中没有收到任何错误。请说乘号有误,但减号是我在代码中写的
  • 我认为我的问题是循环数组,因为如果我点击删除按钮它会给我错误的总数但是当我刷新页面时它现在会计算正确的总数。

标签: javascript html json


【解决方案1】:

根据我认为您要完成的工作,我在下面的代码中制作了一些 cmets。

// cart functionality
table.addEventListener("click", event => { 
    // we can first check if the element does NOT (!) contain the class
    // this means you don't need to wrap the remainder of the code
    // as it will return early when the condition isn't met
    if(!event.target.classList.contains('fa-close')){
        return;
    }

    let removeItem = event.target;
    console.log('df', removeItem);


    let id = removeItem.dataset.id;
    console.log(id);

    table.removeChild(removeItem.parentElement.parentElement);
    
    // should you be setting `obj` to `{}` here? (when it doesn't exist)
    // you can't loop over an object the same way you loop over any array
    // it looks like you should instead set it to `[]`
    let obj = JSON.parse(localStorage.getItem("cart")) || {}; //fetch cart from storage
    
    let items = obj || []; //get the products
    for(let i = 0;i < items.length;i++) { //loop over the collection
        if (items[i].id === id) { //see if ids match
            items.splice(i, 1); //remove item from array
            break; //exit loop
        }
    }

    // you didn't modify `obj` in the previous loop, only `items`
    // should you instead set this to `items` instead of `obj`?
    // if the data exists in localStorage than you would be modifying
    // `obj` directly but in the case it doesn't yet exist
    // you will be returning a `{}` which cannot be looped over
    // the same way you have above
    localStorage.setItem("cart", JSON.stringify(obj)); //set item back into storage

    // decreasing the cart length
    let cal = JSON.parse(localStorage.getItem('cart'));
    if(cal.length !== 0){
        cart_n.innerHTML = `[${cal.length}]`;
    }else{
        cart_n.innerHTML = '';
    }
    
    // define tempTotal outside of the loop
    let tempTotal = 0;
      
    //subtractTotal cart
    cal.find(item => {
        // increment tempTotal by the price using `+=`
        // I removed the `* item.id` as it doesn't make
        // sense multiplying the `price` by the `id`
        tempTotal += item.price;

        // if the item has a `quantity` property
        // you would use this code instead of the line above
        tempTotal += item.price * item.quantity;
    });

    row.innerHTML = tempTotal;
});

【讨论】:

  • 还有一件事,请你帮我写一个更新购物车本地存储的函数
猜你喜欢
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2012-08-11
相关资源
最近更新 更多