要实现一个类似淘宝网商品尺寸价格选择的购物车功能,我们需要考虑以下几个关键点:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商品详情页</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="product">
<h1>商品名称</h1>
<p>请选择尺寸:</p>
<select id="sizeSelect">
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<p>价格: <span id="price">¥0</span></p>
<button onclick="addToCart()">加入购物车</button>
</div>
<script src="script.js"></script>
</body>
</html>
body {
font-family: Arial, sans-serif;
}
.product {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
margin-top: 10px;
padding: 10px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
const sizeSelect = document.getElementById('sizeSelect');
const priceDisplay = document.getElementById('price');
const prices = {
S: 100,
M: 150,
L: 200,
XL: 250
};
sizeSelect.addEventListener('change', () => {
const selectedSize = sizeSelect.value;
const selectedPrice = prices[selectedSize];
priceDisplay.textContent = `¥${selectedPrice}`;
});
function addToCart() {
const selectedSize = sizeSelect.value;
const selectedPrice = prices[selectedSize];
alert(`已添加到购物车: 尺寸 ${selectedSize}, 价格 ¥${selectedPrice}`);
// 这里可以添加更多逻辑,比如将商品信息发送到服务器
}
addToCart
函数,当用户点击“加入购物车”按钮时,弹出一个提示框显示已添加的商品信息。sizeSelect.addEventListener
是否正确执行,确保prices
对象中的数据正确无误。addToCart
函数逻辑有误或未正确调用。addToCart
函数内的逻辑正确,并且在点击按钮时能被正确触发。通过以上代码和解释,你应该能够实现一个基本的仿淘宝网商品尺寸价格选择的购物车功能。如果有更多具体问题或需要进一步扩展功能,可以根据需求进行调整和优化。
没有搜到相关的文章