js购物车添加,加减、删除
时间: 2023-06-27 17:01:28 浏览: 183
好的,以下是一个简单的JavaScript购物车示例,包括添加、增加、减少和删除商品功能:
HTML代码:
```html
<div>
<input type="text" id="item" placeholder="商品名称">
<input type="number" id="price" placeholder="价格">
<button onclick="addItem()">添加</button>
</div>
<ul id="cart"></ul>
```
JavaScript代码:
```javascript
let cart = []; // 购物车数组
function addItem() {
const itemInput = document.getElementById("item");
const priceInput = document.getElementById("price");
// 创建新商品对象
const newItem = {
item: itemInput.value,
price: Number(priceInput.value),
quantity: 1
};
// 判断商品是否已存在于购物车中
const existingItem = cart.find(item => item.item === newItem.item);
if (existingItem) {
existingItem.quantity++;
} else {
cart.push(newItem);
}
// 渲染购物车列表
renderCart();
// 清空输入框
itemInput.value = "";
priceInput.value = "";
}
function increaseQuantity(index) {
cart[index].quantity++;
renderCart();
}
function decreaseQuantity(index) {
cart[index].quantity--;
if (cart[index].quantity === 0) {
cart.splice(index, 1);
}
renderCart();
}
function removeItem(index) {
cart.splice(index, 1);
renderCart();
}
function renderCart() {
const cartList = document.getElementById("cart");
cartList.innerHTML = "";
// 按顺序循环遍历购物车中的商品
cart.forEach((item, index) => {
const li = document.createElement("li");
li.innerHTML = `
<span>${item.item}</span>
<button onclick="increaseQuantity(${index})">+</button>
<span>${item.quantity}</span>
<button onclick="decreaseQuantity(${index})">-</button>
<span>${item.price * item.quantity}元</span>
<button onclick="removeItem(${index})">删除</button>
`;
cartList.appendChild(li);
});
}
```
解释:
1. 首先定义一个空数组 `cart`,用来存储购物车中的商品对象。
2. `addItem` 函数用来添加新商品到购物车中。它首先从输入框中获取商品名称和价格,然后创建一个新的商品对象,并判断它是否已经存在于购物车中。如果是,则将该商品的数量加一;否则,将新商品添加到购物车数组中。最后,调用 `renderCart` 函数更新购物车列表,并清空输入框。
3. `increaseQuantity` 和 `decreaseQuantity` 函数分别用于增加和减少购物车中某个商品的数量。它们接收一个参数 `index`,表示要修改的商品在购物车数组中的索引。修改完成后,调用 `renderCart` 函数更新购物车列表。
4. `removeItem` 函数用于删除购物车中某个商品。它也接收一个参数 `index`,表示要删除的商品在购物车数组中的索引。删除完成后,调用 `renderCart` 函数更新购物车列表。
5. `renderCart` 函数用于渲染购物车列表。它首先获取购物车列表的 DOM 元素,然后循环遍历购物车数组中的每个商品,并创建一个新的 `<li>` 元素来显示商品信息。每个 `<li>` 元素包括商品名称、增加、减少和删除按钮、商品数量和总价。最后,将所有 `<li>` 元素添加到购物车列表中。
以上就是一个简单的JavaScript购物车示例,包括添加、增加、减少和删除商品功能。