在JavaScript中实现购物车商品的加减功能,通常涉及到对商品数量的增减以及总价的实时更新。以下是一个简单的示例代码,展示了如何实现这一功能:
<div class="product">
<span>商品名称</span>
<button class="decrement">-</button>
<input type="number" value="1" min="1" class="quantity">
<button class="increment">+</button>
<span class="price">¥100</span>
</div>
<div class="total-price">总价: ¥<span id="total">100</span></div>
document.addEventListener('DOMContentLoaded', function() {
const quantityInputs = document.querySelectorAll('.quantity');
const totalPriceDisplay = document.getElementById('total');
function updateTotalPrice() {
let total = 0;
quantityInputs.forEach(input => {
const price = parseFloat(input.nextElementSibling.textContent.replace('¥', ''));
total += price * input.value;
});
totalPriceDisplay.textContent = total.toFixed(2);
}
quantityInputs.forEach(input => {
const incrementButton = input.previousElementSibling;
const decrementButton = input.nextElementSibling.previousElementSibling;
incrementButton.addEventListener('click', function() {
input.value = parseInt(input.value) + 1;
updateTotalPrice();
});
decrementButton.addEventListener('click', function() {
if (parseInt(input.value) > 1) {
input.value = parseInt(input.value) - 1;
updateTotalPrice();
}
});
});
});
updateTotalPrice
函数用于计算并更新总价。parseInt
或parseFloat
进行转换。通过上述代码和解释,你应该能够实现一个基本的购物车加减功能,并理解其背后的原理和可能的扩展点。
领取专属 10元无门槛券
手把手带您无忧上云