javascript - LocalStorage 更新元素导致与 JQuery 中的 JSON 重复

标签 javascript jquery html css json

所以我试图用 JSON 更新 LocalStorage 中的一个元素,但我不知道我做错了什么。我想添加一个产品,并在再次添加相同产品时更新其数量。

第一次添加 X 产品时,我在一个元素中获得了正确的数量。添加另一个 X 后,数量将变为空。添加全新的产品 Y,将导致多个重复的 Y 元素且数量全部为空。

一定有一些逻辑错误,我似乎无法弄清楚。我怀疑 addToCart 函数出了问题。由于我是 JavaScript 和 JQuery 的新手,因此非常感谢任何帮助。谢谢。

$(document).ready(function() {
  // caching
  let $table = $(".shoe-table");

  fetch("shoes.json")
    .then(resp => resp.json())
    .then(data => {
      let shoes = data.shoes;
      let rows = [1, 2, 3];
      let shoeCard = "";
      let products = JSON.parse(localStorage.products || "[]");
      console.log(products);

      function addToCart(cBtn) {
        let clickedButton = $(cBtn);
        let buttonID = clickedButton.attr("id");
        let thisInput = $("#" + clickedButton.attr("id") + ".input-form").children("input");
        let newShoe = {
          id: buttonID,
          image: shoes[buttonID].image,
          name: shoes[buttonID].name,
          price: shoes[buttonID].price,
          quantity: parseInt(thisInput.val())
        };

        if (products.length != 0) {
          products.forEach(shoe => {
            if (shoe.name == newShoe.name) {
              shoe.quantity += newShoe.quantity;
              localStorage.setItem("products", JSON.stringify(products));
              console.log(products);
            } else {
              products.push(newShoe);
              localStorage.setItem("products", JSON.stringify(products));
            }
          });
        } else {
          products.push(newShoe);
          localStorage.setItem("products", JSON.stringify(products));
        }
      }

      let counter = 0;
      rows.forEach(row => {
        shoeCard += "<tr>";
        for (let index = 0; index < 4; index++) {
          shoeCard +=
            "<td class='card text-center'>" +
            "<img class='card-img-top' src=" +
            shoes[counter].image +
            " alt='Card image cap'>" +
            "<h5 class='card-title'>" +
            shoes[counter].name +
            "</h5>" +
            "<p class='card-text'>kr " +
            shoes[counter].price +
            "</p>" +
            "<button id=" +
            counter +
            " class='orderNow btn btn-outline-dark'>ORDER NOW</button>" +
            "<div id=" +
            counter +
            " class='input-form'><input class='qty-chooser' type='number' placeholder='Choose quantity' min=0 max=10>" +
            "<button class='btn-add-to-cart' disabled='disabled'>ADD TO CART</button>" +
            "</div>" +
            "</td>";
          counter++;
        }

        shoeCard += "</tr>";
      });

      $table.append(shoeCard);
      let $inputForm = $(".input-form");
      let $orderBtn = $(".orderNow");

      $inputForm.hide();

      let activeButton = -1;

      // Denna metod tittar om man redan har en aktiv beställning
      function isProductActive() {
        let btnID = $(this).attr("id");
        if (activeButton == -1) {
          activeButton = btnID;
          toggleOrder($(this));
        } else if (btnID != activeButton) {
          toggleOrder($("#" + activeButton + ".orderNow"));
          toggleOrder($(this));
          activeButton = btnID;
        } else if (btnID == activeButton) {
          toggleOrder($(this));
          activeButton = -1;
        }
      }

      $orderBtn.click(isProductActive);

      function toggleOrder(buttonC) {
        console.log("INSIDE TOGGLE");
        let clickedBtn = $(buttonC);
        let thisInputForm = $("#" + clickedBtn.attr("id") + ".input-form");

        let inputBtn = thisInputForm.children("button");
        let inputIn = thisInputForm.children("input");

        // RESETTAR ELEMENT I .input-form
        function resetInputForm() {
          inputBtn.css("background", "");
          inputBtn.css("color", "");
          inputBtn.attr("disabled", "disabled");
          inputIn.val(null);
        }

        // DENNA KNAPP ÄR EN ADD TO CART FUNKTION
        inputBtn.click(function() {
          // TODO: LÄGG TILL LOGIK FÖR ATT LÄGGA TILL VARUKORG
          console.log("INSIDE ADDING");

          addToCart(clickedBtn);
          thisInputForm.hide("slow");
          clickedBtn.text("ORDER NOW");
          clickedBtn.css("background", "");
          resetInputForm();
          activeButton = -1;
        });
        // BEROENDE PÅ QUANTITY REAGERAR ADD TO CART KNAPPEN
        inputIn.change(function() {
          let qty = inputIn.val();

          if (qty >= 1 && qty <= 10) {
            inputBtn.removeAttr("disabled");
            inputBtn.css("background", "rgb(15, 163, 10)");
            inputBtn.css("color", "white");
          } else if (qty < 1) {
            resetInputForm();
          } else if (qty > 10) {
            inputIn.val(10);
          }
        });

        // KONTROLLERAR ORDER NOW KNAPPEN
        if (clickedBtn.text() == "CANCEL") {
          thisInputForm.hide("slow");
          clickedBtn.text("ORDER NOW");
          clickedBtn.css("background", "");
          resetInputForm();
        } else {
          thisInputForm.show("slow");
          clickedBtn.text("CANCEL");
          clickedBtn.css("background", "red");
          inputBtn.attr("disabled", "disabled");
          resetInputForm();
        }
      }
    })
    .catch(err => console.error(err));
});

最佳答案

使用以下代码更改 localStorage 代码。问题是您将每次 forEach 迭代上的所有产品推送到 localStorage。

尝试下面的代码。

if (products.length != 0) {
  let isExists = products.some(shoe => shoe.name === newShoe.name);
  if (!isExists) {
    products.push(newShoe);
  } else {
      products = products.map(shoe => {
      if (shoe.name == newShoe.name && !isNaN(newShoe.quantity)) {
        shoe.quantity += newShoe.quantity;
        return shoe;
      }
      return shoe;
    });
  }
  localStorage.setItem("products", JSON.stringify(products));
} else {
  products.push(newShoe);
  localStorage.setItem("products", JSON.stringify(products));
}

关于javascript - LocalStorage 更新元素导致与 JQuery 中的 JSON 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579911/

相关文章:

javascript - 单击 Fabric.js Canvas 时如何获取图像的 src?

javascript - 使元素移动到 div 下方而不在 div 上设置高度

javascript - XMLHttpRequest 访问 Public Dropbox 中的文件

javascript - html 时钟的突然滚动条显示

java - 不需要关闭窗口,如果我按确认框中的取消按钮?

javascript - 在条形图中呈现数据 AngularJS,如何制作一个好的多条形图?

jquery - 动画停止后开始播放

javascript - jQuery .then() 调用两个函数

javascript - Stack Overflow 如何在不重新加载页面的情况下通知服务器端事件?我在 Firebug 中没有看到任何请求

php - 如何使用 AJAX 和 JSON 发送和接收