首页 > 解决方案 > 电子商务网站购物车页面计算和HTMl更新

问题描述

我正在尝试为电子商务网站构建购物车页面。我在计算 JS 时遇到了麻烦。下面我通过 AJAX 调用获取了一个名为 products.json 的文件,其中包含产品信息,如 id、名称、imp、价格等,以及一个名为 productsArray 的数组,其中保存了产品 id我点击了他们各自的购物车图标的产品。现在的逻辑是 products.json 文件是否包含我希望它显示在购物车页面上的数组中存在的产品 id。因此,当我单击产品添加到购物车按钮时,对于我单击的任何产品,它都会被添加到本地存储中,然后我会从那里获取它并将其与 JSON 文件中存在的每个产品进行比较。现在这是用所有提供的信息打印我的产品。现在我想在更改产品数量时更改价格。一世' 我还在下面添加了一个代码,这也有效。当我点击 2 时,价格乘以 2 并以 HTML 形式显示。其他值也类似。问题是这只适用于第一个产品。即使 ID 都相同,我也无法使所有产品的功能都正常工作。我该如何解决这个问题?此外,我需要能够访问所有产品价格,如下面的第二张图片所示,将它们总结起来,然后更新顶部的总数和各种描述下的正确容器。我该怎么做呢?请帮忙!在过去的 3-4 天里一直试图破解这个.. 即使 ID 都相同,我也无法使所有产品的功能都正常工作。我该如何解决这个问题?此外,我需要能够访问所有产品价格,如下面的第二张图片所示,将它们总结起来,然后更新顶部的总数和各种描述下的正确容器。我该怎么做呢?请帮忙!在过去的 3-4 天里一直试图破解这个.. 即使 ID 都相同,我也无法使所有产品的功能都正常工作。我该如何解决这个问题?此外,我需要能够访问所有产品价格,如下面的第二张图片所示,将它们总结起来,然后更新顶部的总数和各种描述下的正确容器。我该怎么做呢?请帮忙!在过去的 3-4 天里一直试图破解这个..

let products = new Set();
let counter = 0;

// adding click events to cart icon
document.body.addEventListener('click', e => {
  if (e.target.closest('.shopping')) {
    products.add(e.target.closest('.prod-card').id);

    // adding number of products in cart icon
    counter = Number(document.querySelector('#cart-badge').innerHTML) + 1;
    document.querySelector('#cart-badge').innerHTML = String(counter);
  };
  // storing product ids in local storage
  localStorage.setItem('Products_IDs', JSON.stringify(Array.from(products)))
});


// parsing JSON List for cart page
let RetrievedData = localStorage.getItem("Products_IDs");
let productsArray = JSON.parse(RetrievedData);

// for (i = 0; i < productsArray.length; i++){
//   console.log(productsArray);
// }


let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    let myProducts = JSON.parse(this.responseText);
    for (i = 0; i < productsArray.length; i++) {
      for (j = 0; j < myProducts.products.length; j++) {
        if (productsArray[i] == myProducts.products[j].id) {
          let ReturnedHTML2 = " ";
          ReturnedHTML2 = `<div class="cart-items-holder" id='pdt-box'>
            <div class='pdt-container' id='pdt-single'>
                <img class='img-sweater' src="Images/${myProducts.products[j].imageName}.png" alt="Sweater Image">
                <div class="pdt-text w-100">
                    <div class="text1">
                        <h6>${myProducts.products[j].name}</h6>
                        <p class="mb-0 text-secondary">Color : Multicolor</p>
                        <p class="mb-0 text-secondary">Seller : Indus Valley & Co</p>
                        <div class="forms mt-xl-3 mt-lg-3 mt-md-2 mt-sm-2 d-flex justify-content-start align-items-start">
                            <div class="form-group">
                                <label class='mr-2' for="exampleFormControlSelectSize"></label>
                                <select class="form-control" id="exampleFormControlSelectSize">
                                    <option>Size : Onesize</option>
                                    <option>S</option>
                                    <option>M</option>
                                    <option>L</option>
                                    <option>XL</option>
                                    <option>XXL</option>
                                </select>
                            </div>
                            <div class="form-group2 ml-3">
                                <label class='mr-2' for="exampleFormControlSelectQuantity"></label>
                                <select class="form-control" id="exampleFormControlSelectQuantity">
                                    <option>QTY : 1</option>
                                    <option>1</option>
                                    <option>2</option>
                                    <option>3</option>
                                    <option>4</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="text2">
                        <p class='pricing mb-0'>Rs.<strong id='final-price'>${myProducts.products[j].priceAfterDiscount}</strong> <del id='initial-price'>Rs.${myProducts.products[j].price}</del><span
                            class="offer font-weight-bold ml-1">(60%Off)</span></p>
                            <small class="text-secondary">Delivery in 4 - 6 days</small>
                    </div>
                </div>
            </div>
            <div class="options">
                <a class="ml-3 mr-3 text-dark font-weight-bold" id='remove-btn' href="">REMOVE</a> | <a class="ml-3 mr-3 text-dark font-weight-bold" id='wishlist-btn' href="">ADD TO WISHLIST</a>
            </div>
        </div>
        <br>`
          document.querySelector('#cart-items-area').innerHTML += ReturnedHTML2;
          sessionStorage.setItem("discounted_price", Number(document.getElementById('final-price').innerHTML))
          document.getElementById('exampleFormControlSelectQuantity').onchange = function() {

            if (document.getElementById('exampleFormControlSelectQuantity').selectedIndex == 1) {
              price_1 = sessionStorage.getItem("discounted_price");
              document.getElementById('final-price').innerHTML = price_1 * 1;
            } else if (document.getElementById('exampleFormControlSelectQuantity').selectedIndex == 2) {
              price_2 = sessionStorage.getItem("discounted_price");
              document.getElementById('final-price').innerHTML = price_2 * 2;
            } else if (document.getElementById('exampleFormControlSelectQuantity').selectedIndex == 3) {
              price_3 = sessionStorage.getItem("discounted_price");
              document.getElementById('final-price').innerHTML = price_3 * 3;
            } else if (document.getElementById('exampleFormControlSelectQuantity').selectedIndex == 4) {
              price_4 = sessionStorage.getItem("discounted_price");
              document.getElementById('final-price').innerHTML = price_4 * 4;
            } else {
              price_default = sessionStorage.getItem("discounted_price");
              document.getElementById('final-price').innerHTML = price_default;
            }
          }
        }
      }
    }
  }
};
xmlhttp.open("GET", "products.json", true);
xmlhttp.send();

[这显示了单击添加到购物车图标以将产品 ID 添加到本地存储并在顶部增加购物车图标值 这显示了从 JSON 列表中通过 JS 呈现的各种产品

标签: javascripthtmlajaxe-commerceshopping-cart

解决方案


看到你已经花了几天的时间。我认为值得花一些时间重构现有代码,使其更有条理!:)

  • 我看到很多嵌套的 if 和 fors => 将它们提取到单独的函数中
  • 我看到一个包含 HTML 文档字符串的大模板 => 带有 2 个参数的单独函数并返回完全呈现的 html 文档。

如果您最终又查看此代码一天,至少将每个部分提取到其自己的更简单的函数中会有所帮助。然后,您还可以单独运行每个函数以测试它是否以这种方式完成了您的预期!:) 它有助于一吨的分裂!

现在,它只是 XMLHTTPRequest 处理程序中的一个“大怪物函数”。


此外,底部有相当多的重复代码,每当您看到它时,它应该有助于指导您在哪里减少和简化您的代码!:

if (document.getElementById('exampleFormControlSelectQuantity').selectedIndex == 1) {
    price_1 = sessionStorage.getItem("discounted_price");
    document.getElementById('final-price').innerHTML = price_1 * 1;
} else if (/*repeated code*/) {
    /* repeated code, with a single number changing 2, 3, 4... */
}

条件代码(几乎)完全相同,因此您不必在每种情况下都对同一元素进行相同的文档查询。

const selected_number = document.getElementById('exampleFormControlSelectQuantity').selectedIndex;

你可以像这样重复使用它:

if (selected_number == 1) {
    price_1 = sessionStorage.getItem("discounted_price");
    document.getElementById('final-price').innerHTML = price_1 * 1;
} else if (selected_number == 2) {
    /* repeated code, with a single number changing 2, 3, 4... */
}

但是现在您也可以假设数字是...条件内需要的数字...因此您可以将单个数字检查缩短为如下代码片段:

price = sessionStorage.getItem("discounted_price");
document.getElementById('final-price').innerHTML = price * selected_number;

推荐阅读