以下是一个简单的前端 JavaScript 示例代码,用于实现将商品添加到购物车的功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>添加购物车示例</title>
</head>
<body>
<div>
<h2>商品列表</h2>
<ul id="product-list">
<li data-id="1" data-name="商品1" data-price="10">商品1 - 价格: 10 元</li>
<li data-id="2" data-name="商品2" data-price="20">商品2 - 价格: 20 元</li>
<li data-id="3" data-name="商品3" data-price="30">商品3 - 价格: 30 元</li>
</ul>
</div>
<div>
<h2>购物车</h2>
<ul id="cart-list"></ul>
</div>
<script>
// 获取商品列表和购物车列表的 DOM 元素
const productList = document.getElementById('product-list');
const cartList = document.getElementById('cart-list');
// 为每个商品项添加点击事件监听器
productList.addEventListener('click', function (event) {
if (event.target.tagName === 'LI') {
const product = event.target;
const productId = product.getAttribute('data-id');
const productName = product.getAttribute('data-name');
const productPrice = product.getAttribute('data-price');
addToCart(productId, productName, productPrice);
}
});
// 添加到购物车的函数
function addToCart(id, name, price) {
let cartItem = document.querySelector(`#cart-list li[data-id="${id}"]`);
if (cartItem) {
// 如果商品已在购物车中,增加数量
let quantity = parseInt(cartItem.getAttribute('data-quantity')) + 1;
cartItem.setAttribute('data-quantity', quantity);
cartItem.textContent = `${name} - 价格: ${price} 元 x ${quantity}`;
} else {
// 如果商品不在购物车中,创建新的购物车项
cartItem = document.createElement('li');
cartItem.setAttribute('data-id', id);
cartItem.setAttribute('data-name', name);
cartItem.setAttribute('data-price', price);
cartItem.setAttribute('data-quantity', 1);
cartItem.textContent = `${name} - 价格: ${price} 元 x 1`;
cartList.appendChild(cartItem);
}
}
</script>
</body>
</html>
在上述示例中:
可能遇到的问题及解决方法:
高校公开课
Elastic 实战工作坊
Elastic 实战工作坊
云+社区技术沙龙[第23期]
腾讯云GAME-TECH沙龙
云+社区技术沙龙[第29期]
云+社区技术沙龙[第26期]
视频云直播活动
云+社区沙龙online [国产数据库]
云+社区沙龙online [国产数据库]
云+社区技术沙龙[第22期]
云+社区技术沙龙[第24期]
领取专属 10元无门槛券
手把手带您无忧上云