欢迎来到我们的线上商店。我们提供各种各样的产品供您选择。浏览我们的商品清单,找到您需要的商品。当你找到想要的商品后,请点击 "添加到购物车" 按钮。
商品清单
购物车
下单
<script>
// 获取购物车元素const cart = document.querySelector('tbody');// 定义购物车商品列表const products = [{ id: 1, name: '商品1', price: 10.00 },{ id: 2, name: '商品2', price: 15.00 },{ id: 3, name: '商品3', price: 20.00 },{ id: 4, name: '商品4', price: 25.00 },{ id: 5, name: '商品5', price: 30.00 },];// 计算总价const calculateTotalPrice = () => {let total = 0.00;for (let i = 0; i < cart.rows.length; i++) {const row = cart.rows[i];const quantity = parseInt(row.cells[1].textContent);const price = parseFloat(row.cells[2].textContent);total += quantity price;}return total.toFixed(2);}// 动态更新购物车商品信息const updateCart = () => {// 清空购物车while (cart.rows.length > 0) {cart.deleteRow(0);}// 遍历购物车中商品for (let i = 0; i < products.length; i++) {// 创建新行const row = cart.insertRow();// 创建单元格const nameCell = row.insertCell(0);const quantityCell = row.insertCell(1);const priceCell = row.insertCell(2);const totalCell = row.insertCell(3);// 设置单元格内容nameCell.textContent = products[i].name;quantityCell.textContent = 1;priceCell.textContent = products[i].price.toFixed(2);totalCell.textContent = products[i].price.toFixed(2);}// 计算并更新总价const totalPrice = calculateTotalPrice();document.getElementById('total-price').textContent = totalPrice;}// 初始化购物车updateCart();
</script>