Javascript 如何从一开始就避免本地存储渲染 代码

Javascript 如何从一开始就避免本地存储渲染 代码,javascript,Javascript,下面是一个函数的代码,当用户单击“添加到购物车”按钮时会触发该函数。它使用localStorage中关于用户从菜单中选择的项目的数据在购物车内创建一行 function addItemToCart() { var cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); var cartItems = document.getElementsBy

下面是一个函数的代码,当用户单击“添加到购物车”按钮时会触发该函数。它使用localStorage中关于用户从菜单中选择的项目的数据在购物车内创建一行

function addItemToCart() {
  
  var cartRow = document.createElement("div");
  cartRow.classList.add("cart-row");
  var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items">
  var cartItemNames = cartItems.getElementsByClassName("cart-item-title");
  //Putting the data
  var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
  var cartRowContents = locStore.map((item) => {
    return `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${item.image}" width="100" height="100">
            <span class="cart-item-title">${item.title}</span>
            <span class="cart-item-size">"Rs.${item.sizePrice}"</span>
        </div>
        <span class="cart-price cart-column">${item.price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>`;
  });
  cartRowContents = cartRowContents.join("");

  cartRow.innerHTML = cartRowContents;
  cartItems.append(cartRow);
  cartRow
    .getElementsByClassName("btn-danger")[0]
    .addEventListener("click", removeCartItem);
  cartRow
    .getElementsByClassName("cart-quantity-input")[0]
    .addEventListener("change", quantityChanged);
}
使用上述数据,我在购物车中创建了一行。到目前为止,它完全可以正常工作。
现在,我在localStorage中添加了另一项,现在localStorage看起来如下所示:-

[{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}]
[{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1},
{"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]"
现在,
addItemToCart()
再次被触发,因为我们选择了另一个项目。这一次,它将在一行中显示两个项目,因为它还将考虑localStorage中实际已考虑的第一个项目。
我应该怎么做来避免这个问题

输出-用户界面(购物车)

类似的内容应该可以(注意,没有整个上下文,我无法测试它):

函数addItemToCart(项){
var cartRow=document.createElement(“div”);
cartRow.classList.add(“cart行”);
var cartimes=document.getElementsByClassName(“购物车项目”)[0]//
var cartItemNames=cartItems.getElementsByClassName(“购物车项目标题”);
//把数据
var cartRowContents=`
${item.title}
“卢比${item.sizePrice}”
${item.price}
去除
`;
cartRowContents=cartRowContents.join(“”);
cartRow.innerHTML=cartRowContents;
cartItems.append(cartRow);
卡特罗
.getElementsByClassName(“btn危险”)[0]
.addEventListener(“单击”,删除部分项目);
卡特罗
.getElementsByClassName(“购物车数量输入”)[0]
.addEventListener(“变更”,数量变更);
}
/**
*渲染购物车中的所有项目,
*将项添加到本地存储后,调用此选项,而不是addItemToCart。
**/
函数renderItemsInCart(){
var cartimes=document.getElementsByClassName(“购物车项目”)[0]//
carItems.innerHTML=“”;
var locStore=JSON.parse(localStorage.getItem(“selectedProduct”);
var cartRowContents=locStore.map((项)=>addItemToCart(项));
}

为什么不访问
locStore
的最后一个元素,因为那是最新的元素,对吗?目前您正在调用
.map
整个localStorage项目,但我假设只有在使用最新项目更新了
localStorage
之后才会调用
addItemToCart
,并且您只希望DOM反映最新的更改。我认为以下方法应该有效:-


 var item = locStore[locStore.length-1];
 var cartRowContents = 
        `<div class="cart-item cart-column">
            <img class="cart-item-image" src="${item.image}" width="100" height="100">
            <span class="cart-item-title">${item.title}</span>
            <span class="cart-item-size">"Rs.${item.sizePrice}"</span>
        </div>
        <span class="cart-price cart-column">${item.price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>`;

变量项=locStore[locStore.length-1];
var cartRowContents=
`
${item.title}
“卢比${item.sizePrice}”
${item.price}
去除
`;

您可以在函数的请求中清空整个购物车,然后让函数从LocalStorage填充所有内容。

我知道答案已被接受,但假设您的商品有一个ID,您可以利用该ID使每个购物车行唯一(用于更新数量和删除购物车商品)

PS:我没有测试这个。这只是为了优化和修复您的UI问题

//add cart item row
function addItemToCart () {
    document.getElementsByClassName("cart-items")[0].insertAdjacentHTML(
        'beforeend',
        `<div class="cart-row" id="cartid-${item.id}">
            <div class="cart-item cart-column">
                <img class="cart-item-image" src="${item.image}" width="100" height="100">
                <span class="cart-item-title">${item.title}</span>
                <span class="cart-item-size">"Rs.${item.sizePrice}"</span>
            </div>
            <span class="cart-price cart-column">${item.price}</span>
            <div class="cart-quantity cart-column">
                <input class="cart-quantity-input" type="number" value="1" id="quantityid-${item.id} onchange="quantityChanged">
                <button class="btn btn-danger" type="button" onclick="removeCartItem(this)">REMOVE</button>
            </div>
        </div>`      
    )
}

//remove the cart item row
function removeCartItem (input) {
    input.parentNode.remove()
}


/**
 * Render all the items in cart, 
 * call this instead of addItemToCart after an item was added to local storage.
 **/
function renderItemsInCart() {
  var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items">
  carItems.innerHTML = "";
  var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
  var cartRowContents = locStore.map((item) => addItemToCart(item));
}

//添加购物车项目行
函数addItemToCart(){
document.getElementsByClassName(“购物车项目”)[0]。insertAdjacentHTML(
"之前",,
`
${item.title}
“卢比${item.sizePrice}”
${item.price}

只需检查是否已经存在具有产品id的项目,并跳过该项。是的,“Tandoori Pizza”是localStorage中的第一个对象,因此,一旦我单击“添加到购物车”按钮,它就会立即添加到购物车中,然后我在购物车中添加“Veggie Supreme”。我现在单击“添加到”按钮的那一刻,它就会考虑已经存在的“Tandoori Pizza”在localStorage中,并与“Veggie Supreme”一起显示在购物车中。感谢您的回答,使用您的代码,它多次显示项目,但显示在不同的行中。之前,它在一行中显示两个项目。现在,它在不同的行中显示每个项目。是的,很抱歉,我忘了清理购物车,请立即尝试。显然,通过保存渲染行列表或在DOM中查找它们,我们可以做得更好。B但是这个解决方案是最接近你已经拥有的,所以让我们先试试吧,它非常有效。非常感谢。你的方法似乎很好。我会试试。谢谢。是的。我后来意识到我应该使用这里的ID。谢谢你的回答。
//add cart item row
function addItemToCart () {
    document.getElementsByClassName("cart-items")[0].insertAdjacentHTML(
        'beforeend',
        `<div class="cart-row" id="cartid-${item.id}">
            <div class="cart-item cart-column">
                <img class="cart-item-image" src="${item.image}" width="100" height="100">
                <span class="cart-item-title">${item.title}</span>
                <span class="cart-item-size">"Rs.${item.sizePrice}"</span>
            </div>
            <span class="cart-price cart-column">${item.price}</span>
            <div class="cart-quantity cart-column">
                <input class="cart-quantity-input" type="number" value="1" id="quantityid-${item.id} onchange="quantityChanged">
                <button class="btn btn-danger" type="button" onclick="removeCartItem(this)">REMOVE</button>
            </div>
        </div>`      
    )
}

//remove the cart item row
function removeCartItem (input) {
    input.parentNode.remove()
}


/**
 * Render all the items in cart, 
 * call this instead of addItemToCart after an item was added to local storage.
 **/
function renderItemsInCart() {
  var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items">
  carItems.innerHTML = "";
  var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
  var cartRowContents = locStore.map((item) => addItemToCart(item));
}