You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击单个商品删除按钮仅修改对应商品的数量值

Fix: Clicking "Supprimer" Only Updates Corresponding Product Quantity

Hey there! The problem with your current code is that every time you click a delete button, it loops through all .qte elements on the page and decrements each one. Instead, we need to target only the quantity element that's part of the same product entry as the clicked button.

Here's the Modified JavaScript Code

const suppr = document.querySelectorAll('.suppr');
suppr.forEach(function(button) {
  button.onclick = (event => {
    // Locate the parent product container (the closest .list-group-item)
    const productContainer = button.closest('.list-group-item');
    // Find the specific .qte element inside this product container
    const targetQtyElement = productContainer.querySelector('.qte');
    
    // Calculate and update the quantity (with a check to avoid negative values)
    let currentQuantity = parseInt(targetQtyElement.innerText);
    if (currentQuantity > 0) {
      targetQtyElement.innerText = currentQuantity - 1;
    }
  })
});

How This Works

  1. Target the Right Container: Using button.closest('.list-group-item'), we traverse up the DOM from the clicked button to find the nearest parent element that wraps the entire product (including its quantity and delete button). This ensures we're only working with the relevant product's elements.
  2. Select the Specific Quantity Element: Instead of grabbing all .qte elements on the page, we use productContainer.querySelector('.qte') to pick only the quantity element inside the targeted product container.
  3. Safe Quantity Update: We add a check to make sure the quantity doesn't drop below 0—this prevents odd behavior if a user clicks delete when the quantity is already 1.

Why Your Original Code Failed

Your original code used document.querySelectorAll('.qte') to get all quantity elements, then looped through every single one to decrement the value. That's why clicking any delete button affected every product's quantity. By narrowing our scope to the product container linked to the clicked button, we fix this issue.

内容的提问来源于stack exchange,提问作者Mehdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:08:36