用前端语言写一段实现购物车的代码
时间: 2023-11-28 19:47:28 浏览: 144
好的,以下是一个简单的购物车代码示例,使用了HTML、CSS和JavaScript:
HTML代码:
```
<div class="cart">
<h2>购物车</h2>
<ul id="cart-list"></ul>
<p id="total">总价:0元</p>
<button id="checkout">结算</button>
</div>
<div class="products">
<h2>商品列表</h2>
<ul>
<li>
<span class="name">商品1</span>
<span class="price">100元</span>
<button class="add-to-cart" data-name="商品1" data-price="100">加入购物车</button>
</li>
<li>
<span class="name">商品2</span>
<span class="price">50元</span>
<button class="add-to-cart" data-name="商品2" data-price="50">加入购物车</button>
</li>
<li>
<span class="name">商品3</span>
<span class="price">200元</span>
<button class="add-to-cart" data-name="商品3" data-price="200">加入购物车</button>
</li>
</ul>
</div>
```
CSS代码:
```
.cart {
float: left;
width: 300px;
padding: 20px;
border: 1px solid #ccc;
}
.cart h2 {
margin-top: 0;
}
.cart ul {
list-style: none;
padding: 0;
}
.cart li {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
.products {
float: left;
width: 500px;
padding: 20px;
border: 1px solid #ccc;
}
.products h2 {
margin-top: 0;
}
.products ul {
list-style: none;
padding: 0;
}
.products li {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
.add-to-cart {
background-color: #337ab7;
color: #fff;
border: none;
padding: 5px 10px;
cursor: pointer;
}
.add-to-cart:hover {
background-color: #23527c;
}
```
JavaScript代码:
```
// 获取DOM元素
const cartList = document.getElementById('cart-list');
const total = document.getElementById('total');
const checkoutBtn = document.getElementById('checkout');
const addToCartBtns = document.getElementsByClassName('add-to-cart');
// 初始化购物车数据
let cartData = [];
// 加入购物车事件监听
for (let i = 0; i < addToCartBtns.length; i++) {
addToCartBtns[i].addEventListener('click', function() {
const name = this.getAttribute('data-name');
const price = Number(this.getAttribute('data-price'));
const item = { name, price };
cartData.push(item);
renderCart();
});
}
// 渲染购物车
function renderCart() {
let html = '';
let totalPrice = 0;
for (let i = 0; i < cartData.length; i++) {
html += `<li>${cartData[i].name} - ${cartData[i].price}元</li>`;
totalPrice += cartData[i].price;
}
cartList.innerHTML = html;
total.innerHTML = `总价:${totalPrice}元`;
}
// 结算事件监听
checkoutBtn.addEventListener('click', function() {
alert(`总价:${total.innerText}`);
cartData = [];
renderCart();
});
```
这段代码实现了一个简单的购物车功能,包括商品列表、加入购物车和结算等功能。当用户点击“加入购物车”按钮时,将商品信息添加到购物车数据中并渲染到页面上;当用户点击“结算”按钮时,弹出总价并清空购物车数据。
阅读全文