电子商务网站购物车页面计算和 HTMl 更新

E-commerce website cart page calculation and HTMl updation

我正在尝试为电子商务网站构建购物车页面。我在弄清楚用于计算的 JS 时遇到了麻烦。下面我通过 AJAX 调用获取了一个名为 products.json 的文件,其中包含产品信息,如 id、名称、imp、价格等和一个名为的数组productsArray,它保存了我点击各自购物车图标的产品的产品 ID。现在的逻辑是,如果 products.json 文件包含数组中存在的产品 ID,我希望它显示在购物车页面上。因此,当我单击产品添加到购物车按钮时,无论我单击哪个产品,它都会被添加到本地存储中,然后我从那里获取它并将其与 JSON 文件中存在的每个产品进行比较。现在这是用所有提供的信息打印我的产品。现在我想在产品数量改变时改变价格。我还在下面添加了一个代码,它也有效。当我单击 2 时,价格会乘以 2 并显示在 HTML 中。其他值也类似。问题是这仅适用于第一个产品。即使 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();

[

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

  • 我看到很多嵌套的 ifs 和 fors => 将它们提取为单独的函数
  • 我看到一个包含 HTML 文档字符串的大模板 => 带有 2 个参数的单独函数和 returns 完全呈现的 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;