简体   繁体   English

如何将相同的商品添加到购物车

[英]How to Add same item to cart

i want on this website to be able to add the same item to the cart but without creating a new row.我希望在这个网站上能够将相同的商品添加到购物车但不创建新行。 With if (cartItemNames[i].innerText == title) {alert('This item is already added to the cart')return i prevent the user from adding the same item to the cart and an alert popup.使用if (cartItemNames[i].innerText == title) {alert('This item is already added to the cart')return我会阻止用户将相同的项目添加到购物车并弹出警报。

how would i have to proceed if i want to target the cartItemNames[i] element from the loop to get the quantity input from the same row as that cartItemNames[i] element?如果我想从循环中定位 cartItemNames[i] 元素以从与该 cartItemNames[i] 元素相同的行获取数量输入,我将如何继续?

Then i would just add one to the value and set the value?然后我只需将值加一并设置值?

But than i will have to use the parent method on the cartItemNames[i] element in conjunction with the getElementsByClassName to find the row of the cart and then the quantity input in that row.但是,我必须使用 cartItemNames[i] 元素上的父方法和 getElementsByClassName 来查找购物车的行,然后在该行中输入数量。

That brings me to another question, how to find the row of the cart and then the quantity input in that row?这给我带来了另一个问题,如何找到购物车的行以及该行中输入的数量?

function addItemToCart(title, price, imageSrc) {
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == title) {
            alert('This item is already added to the cart')
            return
        }
    }
    var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
        </div>
        <span class="cart-price cart-column">${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>`
    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
    cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}

JSFiddle: https://jsfiddle.net/sigurd14/3z2c9hjn/1/ JSFiddle: https://jsfiddle.net/sigurd14/3z2c9hjn/1/

This works fine, given the scenario.考虑到这种情况,这很好用。

Just check for the existence of the row containing the title you are adding.只需检查包含您要添加的标题的行是否存在。 I suggest you use IDs for uniqueness.我建议您使用 ID 来实现唯一性。

Also, use querySelector and querySelectorAll to make your code look cleaner and to remove checks for index of zero.此外,使用querySelectorquerySelectorAll使您的代码看起来更干净,并删除对零索引的检查。

function addItemToCart(title, price, imageSrc) {
  const exists = [...document.querySelectorAll('.cart-row')].find(row => {
    const target = row.querySelector('.cart-item-title');
    return target && target.textContent === title;
  });

  if (exists) {
    const input = exists.querySelector('.cart-quantity-input');
    input.value = parseInt(input.value, 10) + 1;
  } else {
    var cartItems = document.querySelector('.cart-items');
    var cartRow = document.createElement('div');
    var cartRowContents = `
      <div class="cart-item cart-column">
        <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
          <span class="cart-item-title">${title}</span>
      </div>
      <span class="cart-price cart-column">${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>`
    cartRow.classList.add('cart-row');
    cartRow.innerHTML = cartRowContents;
    cartItems.append(cartRow);
    cartRow.querySelector('.btn-danger').addEventListener('click', removeCartItem);
    cartRow.querySelector('.cart-quantity-input').addEventListener('change', quantityChanged);
  }
}

You just need to find the right selectors for the row columns you added.您只需要为您添加的行列找到正确的选择器。 Since you didn't assign rows really per item you have to go by the index of the columns per item you find.由于您没有真正为每个项目分配行,因此您必须通过您找到的每个项目的列索引来 go 。 I updated the fiddle you posted and this updates the quantity and cart total我更新了您发布的小提琴,这更新了数量和购物车总数

function addItemToCart(title, price, imageSrc) {
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == title) {
            //alert('This item is already added to the cart')
            var priceCol=cartItems.getElementsByClassName('cart-price')[i];
            var qty=cartItems.getElementsByClassName('cart-quantity-input')[i];
            qty.value=parseInt(qty.value)+1;
            return
        }
    }
    var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
        </div>
        <span class="cart-price cart-column">${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>`
    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
    cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}

function updateCartTotal() {
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    for (var i = 0; i < cartRows.length; i++) {
        var cartRow = cartRows[i]
        var priceElement = cartRow.getElementsByClassName('cart-price')[0]
        var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0];
        var price = parseFloat(priceElement.innerText.replace('$', '')).toFixed(2);
        var quantity = quantityElement.value
        total = total + (price * quantity)
    }
    total = Math.round(total * 100) / 100
    document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}

https://jsfiddle.net/z26bwhk1/1/ https://jsfiddle.net/z26bwhk1/1/

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

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