JavaScript购物车加减计算总价是指在前端页面上,通过JavaScript实现对购物车中商品数量的增加或减少,并实时计算出购物车中所有商品的总价。
以下是一个简单的JavaScript示例,展示了如何实现购物车中商品的加减功能并实时计算总价:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车示例</title>
</head>
<body>
<div id="cart">
<div class="item">
<span>商品A - ¥10</span>
<button onclick="decrement(this)">-</button>
<input type="number" value="0" min="0" onchange="updateTotal()">
<button onclick="increment(this)">+</button>
</div>
<div class="item">
<span>商品B - ¥20</span>
<button onclick="decrement(this)">-</button>
<input type="number" value="0" min="0" onchange="updateTotal()">
<button onclick="increment(this)">+</button>
</div>
</div>
<div>总价: ¥<span id="total">0</span></div>
<script>
const prices = {
'商品A': 10,
'商品B': 20
};
function increment(button) {
const input = button.previousElementSibling;
input.value = parseInt(input.value) + 1;
updateTotal();
}
function decrement(button) {
const input = button.nextElementSibling;
if (parseInt(input.value) > 0) {
input.value = parseInt(input.value) - 1;
updateTotal();
}
}
function updateTotal() {
let total = 0;
document.querySelectorAll('#cart .item input').forEach(input => {
const productName = input.parentElement.querySelector('span').textContent.split(' - ')[0];
total += parseInt(input.value) * prices[productName];
});
document.getElementById('total').textContent = total;
}
</script>
</body>
</html>parseInt或parseFloat进行类型转换,并仔细检查逻辑。通过以上方法,可以有效实现并优化购物车的加减功能及总价计算。
没有搜到相关的沙龙