如何使用JavaScript实现简单购物小表格

发布时间:2021-09-29 10:47:58 作者:小新
来源:亿速云 阅读:200
# 如何使用JavaScript实现简单购物小表格

在现代Web开发中,动态交互式表格是电商网站的核心组件之一。本文将详细介绍如何使用原生JavaScript构建一个功能完整的购物小表格,包含商品添加、数量修改、价格计算和删除等功能。

## 一、项目概述

### 1.1 功能需求
- 显示商品列表(名称、单价、数量、小计)
- 支持动态添加新商品
- 可修改商品数量(支持增减按钮)
- 自动计算单项小计和订单总价
- 提供删除商品功能
- 数据本地存储(localStorage)

### 1.2 技术栈
- HTML5/CSS3 基础结构
- 原生JavaScript ES6+
- 本地存储API

## 二、HTML结构搭建

```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>购物小表格</title>
    <style>
        /* 样式部分将在CSS章节展示 */
    </style>
</head>
<body>
    <div class="shopping-cart">
        <h2>我的购物车</h2>
        
        <!-- 商品表格 -->
        <table id="cartTable">
            <thead>
                <tr>
                    <th>商品名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="cartBody"></tbody>
            <tfoot>
                <tr>
                    <td colspan="3">总计</td>
                    <td id="totalPrice">0.00</td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
        
        <!-- 添加商品表单 -->
        <div class="add-product">
            <input type="text" id="productName" placeholder="商品名称">
            <input type="number" id="productPrice" placeholder="单价" min="0" step="0.01">
            <button id="addBtn">添加商品</button>
        </div>
    </div>

    <script src="cart.js"></script>
</body>
</html>

三、CSS样式设计

.shopping-cart {
    max-width: 800px;
    margin: 20px auto;
    font-family: 'Arial', sans-serif;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

th, td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

th {
    background-color: #f2f2f2;
}

.quantity-control {
    display: flex;
    align-items: center;
}

.quantity-btn {
    width: 25px;
    height: 25px;
    background: #f0f0f0;
    border: none;
    cursor: pointer;
    font-size: 16px;
}

.quantity-input {
    width: 40px;
    text-align: center;
    margin: 0 5px;
}

.delete-btn {
    background: #ff4d4d;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 3px;
    cursor: pointer;
}

.add-product {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

.add-product input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

#addBtn {
    padding: 8px 15px;
    background: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

四、JavaScript核心实现

4.1 初始化数据结构

// cart.js
let cartItems = JSON.parse(localStorage.getItem('cart')) || [];

// 示例初始数据
const sampleItems = [
    { id: 1, name: '苹果', price: 5.99, quantity: 2 },
    { id: 2, name: '香蕉', price: 3.50, quantity: 3 }
];

if (cartItems.length === 0) {
    cartItems = sampleItems;
    saveToLocalStorage();
}

4.2 渲染表格函数

function renderCart() {
    const cartBody = document.getElementById('cartBody');
    const totalPriceElement = document.getElementById('totalPrice');
    
    cartBody.innerHTML = '';
    let total = 0;
    
    cartItems.forEach(item => {
        const row = document.createElement('tr');
        const subtotal = item.price * item.quantity;
        total += subtotal;
        
        row.innerHTML = `
            <td>${item.name}</td>
            <td>¥${item.price.toFixed(2)}</td>
            <td>
                <div class="quantity-control">
                    <button class="quantity-btn minus" data-id="${item.id}">-</button>
                    <input type="number" class="quantity-input" value="${item.quantity}" min="1" data-id="${item.id}">
                    <button class="quantity-btn plus" data-id="${item.id}">+</button>
                </div>
            </td>
            <td>¥${subtotal.toFixed(2)}</td>
            <td><button class="delete-btn" data-id="${item.id}">删除</button></td>
        `;
        
        cartBody.appendChild(row);
    });
    
    totalPriceElement.textContent = `¥${total.toFixed(2)}`;
}

4.3 事件处理与功能实现

// 添加商品
document.getElementById('addBtn').addEventListener('click', () => {
    const nameInput = document.getElementById('productName');
    const priceInput = document.getElementById('productPrice');
    
    if (!nameInput.value || !priceInput.value) {
        alert('请填写完整的商品信息');
        return;
    }
    
    const newItem = {
        id: Date.now(), // 使用时间戳作为唯一ID
        name: nameInput.value,
        price: parseFloat(priceInput.value),
        quantity: 1
    };
    
    cartItems.push(newItem);
    saveToLocalStorage();
    renderCart();
    
    // 清空输入框
    nameInput.value = '';
    priceInput.value = '';
});

// 事件委托处理动态元素
document.getElementById('cartBody').addEventListener('click', (e) => {
    const target = e.target;
    const id = parseInt(target.dataset.id);
    
    // 删除商品
    if (target.classList.contains('delete-btn')) {
        cartItems = cartItems.filter(item => item.id !== id);
        saveToLocalStorage();
        renderCart();
    }
    
    // 增加数量
    else if (target.classList.contains('plus')) {
        const item = cartItems.find(item => item.id === id);
        if (item) item.quantity++;
        saveToLocalStorage();
        renderCart();
    }
    
    // 减少数量
    else if (target.classList.contains('minus')) {
        const item = cartItems.find(item => item.id === id);
        if (item && item.quantity > 1) {
            item.quantity--;
            saveToLocalStorage();
            renderCart();
        }
    }
});

// 手动输入数量
document.getElementById('cartBody').addEventListener('change', (e) => {
    if (e.target.classList.contains('quantity-input')) {
        const id = parseInt(e.target.dataset.id);
        const quantity = parseInt(e.target.value);
        
        if (quantity > 0) {
            const item = cartItems.find(item => item.id === id);
            if (item) {
                item.quantity = quantity;
                saveToLocalStorage();
                renderCart();
            }
        } else {
            e.target.value = 1;
        }
    }
});

// 本地存储函数
function saveToLocalStorage() {
    localStorage.setItem('cart', JSON.stringify(cartItems));
}

// 初始化渲染
document.addEventListener('DOMContentLoaded', renderCart);

五、功能扩展建议

  1. 批量操作:添加”全选/反选”和”批量删除”功能
  2. 优惠券系统:实现折扣计算逻辑
  3. 商品分类:按类别分组显示商品
  4. 响应式设计:优化移动端显示效果
  5. 动画效果:添加商品时的过渡动画

六、总结

通过约150行代码,我们实现了一个功能完整的购物小表格系统。关键点包括: - 使用数组存储商品数据 - 通过事件委托处理动态元素 - 实现数据持久化存储 - 自动计算价格逻辑

这个示例展示了如何使用原生JavaScript构建交互式Web应用,为进一步开发更复杂的电商系统奠定了基础。

完整代码可在GitHub仓库获取:[示例仓库链接] “`

(注:实际字数约1800字,此处为保持简洁略有缩减,完整实现可扩展细节说明和代码注释)

推荐阅读:
  1. python实现简单购物筛选
  2. python如何实现简单的购物程序

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript

上一篇:python中如何实现绑定方法与非绑定方法

下一篇:怎样安装启动MongoDB

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》