简体   繁体   English

电商网站购物车页面计算及HTMl更新

[英]E-commerce website cart page calculation and HTMl updation

I'm trying to build a cart page for an e-commerce website.我正在尝试为电子商务网站构建购物车页面。 I'm having trouble figuring out the JS for calculating.. below I'm getting a file through AJAX call called products.json which has products information like id, name, imp, prices etc and an array called productsArray which has product ids saved of products I've clicked on their respective cart icons.我无法弄清楚用于计算的 JS .. 下面我通过 AJAX 调用获得一个名为 products.json 的文件,其中包含产品信息,如 id、名称、imp、价格等,以及一个名为 productsArray 的数组,其中保存了产品 id我点击了他们各自的购物车图标的产品。 Now the logic is if the products.json file contains the id of products present in the array I want it to display on the cart page.现在的逻辑是,如果 products.json 文件包含我希望它显示在购物车页面上的数组中的产品 ID。 So when I click the products add to cart button, for whichever product I click it gets added to local storage and from there I get it and compare it with each of the products present in the JSON file.因此,当我单击产品添加到购物车按钮时,对于我单击的任何产品,它都会被添加到本地存储中,然后我会从那里得到它并将其与 JSON 文件中存在的每个产品进行比较。 Now this is printing my product with all furnished information.现在这是用所有提供的信息打印我的产品。 Now I want to change the price when the quantity of product is changed.现在我想在更改产品数量时更改价格。 I've also added a code fo that below and that too works.我还在下面添加了一个代码,这也有效。 When I click on 2 then the price gets multiplied by 2 and showcases it in HTML.当我点击 2 时,价格乘以 2 并显示在 HTML 中。 similarly for other values.其他值也类似。 The problem is this works only for the first product.问题是这只适用于第一个产品。 I'm unable to get the functionality working for all products even though the IDs are all same.. How do I tackle this issue?即使 ID 都相同,我也无法使所有产品的功能都正常工作。我该如何解决这个问题? Also I need to be able to access all the product prices as you can see in the second image below, sum them up then update the total on the top and the right containers under various descriptions.. How do I do these as well?此外,我需要能够访问所有产品价格,如下面的第二张图片所示,将它们总结起来,然后更新顶部的总数和各种描述下的正确容器。我该怎么做呢? Pls help.请帮忙。 Have been trying to crack this for past 3-4 days..在过去的 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 呈现的各种产品

Seeing that you've spent a few days on this already.看到你已经花了几天的时间。 I would consider it worth spending some time to refactor the existing code to be a bit more organized: :)我认为值得花一些时间将现有代码重构为更有条理::)

  • I see a lot of nested ifs and fors => extract them to separate functions我看到很多嵌套的 if 和 fors => 将它们提取到单独的函数中
  • I see a big template containing an HTML document string => separate function taking 2 arguments & returns the fully rendered html document.我看到一个包含 HTML 文档字符串的大模板 => 单独的 function 采用 2 arguments 并返回完全呈现的 ZCFC35FDC70D5FC67AE2362 文档。

If you end up looking at this code for yet another day, at least it would help if you extracted every part into its own simpler function.如果您最终又查看此代码一天,至少如果您将每个部分提取到其自己更简单的 function 中会有所帮助。 you can also then run each function individually to test that it does what you expect this way: :) It helps a tonne to split things up!然后,您还可以单独运行每个 function 以测试它是否按照您的预期进行::) 它有助于一吨的拆分!

Right now it's all one "big monster function" in the XMLHTTPRequest handler.现在它是 XMLHTTPRequest 处理程序中的一个“大怪物功能”。


Also, there is a fair bit of repeated code in the bottom, Whenever you see this it should help guide you to where to reduce and simplify your code a bit::此外,底部有相当多的重复代码,每当您看到它时,它应该有助于指导您在哪里减少和简化您的代码:

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... */
}

the conditional code is (almost) exactly the same, so you don't have to make the same document query for the same element in every case.条件代码(几乎)完全相同,因此您不必在每种情况下都对同一元素进行相同的文档查询。

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

and you can re-use this like this:你可以像这样重复使用它:

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... */
}

but now you can also just assume the number is... the number you need inside the conditional... so you can shorten the individual number checks to a single snippet of code like this:但是现在您也可以假设数字是...条件内需要的数字...因此您可以将单个数字检查缩短为如下代码片段:

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

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

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