购物车JS代码
以下是一个简单的购物车JS代码示例:
// 1. 获取商品列表
const productList = document.querySelectorAll('.product');
// 2. 为每个商品添加点击事件监听器
productList.forEach(product => {
const addButton = product.querySelector('.add-button');
addButton.addEventListener('click', () => {
// 3. 获取商品名称和价格
const name = product.querySelector('.product-name').innerText;
const price = Number(product.querySelector('.product-price').innerText);
// 4. 创建购物车商品对象
const item = {
name: name,
price: price,
quantity: 1
}
// 5. 将商品添加到购物车
addItemToCart(item);
// 6. 更新购物车总价和数量
updateCartTotal();
});
});
// 7. 添加商品到购物车
function addItemToCart(item) {
const cartItem = document.createElement('div');
cartItem.classList.add('cart-item');
const cartItems = document.querySelector('.cart-items');
// 检查购物车中是否已经存在该商品
const existingCartItem = cartItems.querySelector(`[data-name="${item.name}"]`);
if (existingCartItem) {
// 如果存在,更新商品数量
const quantity = Number(existingCartItem.querySelector('.cart-item-quantity').innerText) + 1;
existingCartItem.querySelector('.cart-item-quantity').innerText = quantity;
return;
}
// 如果不存在,创建新的购物车商品
const cartItemContent = `
<span class="cart-item-name" data-name="${item.name}">${item.name}</span>
<span class="cart-item-price">${item.price}</span>
<span class="cart-item-quantity">1</span>
<button class="cart-item-remove">删除</button>
`;
cartItem.innerHTML = cartItemContent;
cartItems.appendChild(cartItem);
// 为删除按钮添加点击事件监听器
const removeButton = cartItem.querySelector('.cart-item-remove');
removeButton.addEventListener('click', () => {
cartItem.remove();
updateCartTotal();
});
}
// 8. 更新购物车总价和数量
function updateCartTotal() {
const cartItems = document.querySelectorAll('.cart-item');
const cartTotal = document.querySelector('.cart-total');
let total = 0;
let quantity = 0;
cartItems.forEach(cartItem => {
const price = Number(cartItem.querySelector('.cart-item-price').innerText);
const quantity = Number(cartItem.querySelector('.cart-item-quantity').innerText);
total += price * quantity;
quantity += quantity;
});
cartTotal.innerText = `总价:${total},数量:${quantity}`;
}
该示例实现了以下功能:
- 获取商品列表,并为每个商品添加点击事件监听器
- 点击商品的“添加到购物车”按钮时,获取商品名称和价格,创建购物车商品对象,并将其添加到购物车中
- 如果购物车中已经存在相同的商品,更新商品数量,否则创建新的购物车商品对象
- 更新购物车总价和数量,包括每个购物车商品的价格和数量
- 为每个购物车商品的“删除”按钮添加点击事件监听器,从购物车中删除该商品,并更新购物车总价和数量
原文地址: http://www.cveoy.top/t/topic/bd9e 著作权归作者所有。请勿转载和采集!