如何实现点击单个商品删除按钮仅修改对应商品的数量值
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
- 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. - Select the Specific Quantity Element: Instead of grabbing all
.qteelements on the page, we useproductContainer.querySelector('.qte')to pick only the quantity element inside the targeted product container. - 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
相关产品推荐
相关产品推荐

