实现简易购物车

  1. 点击购买页面html
<!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>Document</title>
    <style>
        table {
            border-collapse: collapse;
        }

        td {
            border: 1px solid;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <td>商品名</td>
            <td>价格</td>
            <td>操作</td>
        </tr>
        <tr>
            <td><input type="hidden" value="1">水杯</td>
            <td>29</td>
            <td><a class="buy" href="javascript:;">购买</a></td>
        </tr>
        <tr>
            <td><input type="hidden" value="2">电脑</td>
            <td>4999</td>
            <td><a class="buy" href="javascript:;">购买</a></td>
        </tr>
        <tr>
            <td><input type="hidden" value="3">手机</td>
            <td>1999</td>
            <td><a class="buy" href="javascript:;">购买</a></td>
        </tr>
    </table>
    <button>查看购物车</button>
    <script src="js/product.js"></script>
</body>

</html>

2.js点击购买部分

/*
    1. 跳转到构物车按钮 - 点击 - 跳转
    2. 购买按钮 - 遍历 - 添加点击事件
        1》 获取购物车所需要的信息
        2》 存储在localStorage中
*/
class Product {
    constructor() {
        //获取购物车按钮
        this.cart_btn = document.querySelector('button');
        //获取所有的购买按钮
        this.buys = document.querySelectorAll('.buy');
        //调用添加事件的方法
        this.addEvent();
    }
    addEvent() {
        this.cart_btn.onclick = function () {
            location.href = 'cart.html';
        }
        for (let i = 0, len = this.buys.length; i < len; i++) {
            this.buys[i].count = 0;
            this.buys[i].onclick = function () {
                // 商品ID
                let good_id = this.parentNode.parentNode.firstElementChild.firstElementChild.value;
                // alert(good_id);
                //商品名称
                let good_name = this.parentNode.parentNode.firstElementChild.lastChild.nodeValue;
                // alert(good_name);

                //商品价格
                let good_price = this.parentNode.previousElementSibling.innerText;
                // alert(good_price);

                //商品数量
                this.count++;

                /*
                key : value  
                key  'product_' + good_id
                value : '{"id" : 1,"name" : "水杯","price" : "39","num" : 3}'
                        `{"id" : ${good_id},"name" : "${good_name}","price" : "${good.price}","num" : ${this.count}}`
                */
                //本地存储 
                window.localStorage.setItem(`product_${good_id}`, `{"id" : ${good_id},"name" : "${good_name}","price" : "${good_price}","num" : ${this.count}}`);
            }
        }
    }
}
new Product();

3.购买显示页面html

<!doctype html>
<html>

<head>
    <meta charset="utf-8" />
    <title>JavaScript</title>
    <style>
        table {
            border-collapse: collapse;
        }

        td {
            border: 1px solid;
        }
    </style>

</head>

<body>
    <table id="tab">
        <tr>
            <td>序号</td>
            <td>商品名称</td>
            <td>商品单价</td>
            <td>数量</td>
        </tr>
    </table>
    <script src="js/cart.js"></script>
</body>

</html>

4.购买显示页面js部分

/*
    //1. 拿回localStorage中的数据--过滤出自己的商品
    //2. 动态添加到页面中
*/
class Cart{
    constructor(){
        this.tab = document.querySelector('#tab');
        this.init();
    }
    init() {
        let storage = window.localStorage;
        for(let i = 0;i < storage.length;i ++){
            let key = storage.key(i);
            if(key.startsWith('product_')){
                let good = JSON.parse(storage.getItem(key));

                //在表格中插入一行
                let _tr = this.tab.insertRow();
                //在行中插入td
                let _td = _tr.insertCell();
                _td.innerText = good.id;

                _td = _tr.insertCell();
                _td.innerText = good.name;

                _td = _tr.insertCell();
                _td.innerText = good.price;

                _td = _tr.insertCell();
                _td.innerText = good.num;
            }
        }
    }
}
new Cart();
好的,以下是一个简单的HTML代码实现简易购物车的示例: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>简易购物车</title> </head> <body> <h1>商品列表</h1> <ul> <li> <span>商品1</span> <span>100元</span> <button onclick="addToCart(1)">添加到购物车</button> </li> <li> <span>商品2</span> <span>200元</span> <button onclick="addToCart(2)">添加到购物车</button> </li> <li> <span>商品3</span> <span>300元</span> <button onclick="addToCart(3)">添加到购物车</button> </li> <li> <span>商品4</span> <span>400元</span> <button onclick="addToCart(4)">添加到购物车</button> </li> </ul> <h1>购物车</h1> <ul id="cart"> </ul> <p>总价:<span id="totalPrice">0</span>元</p> <script> // 初始化商品列表和购物车 const products = [ { id: 1, name: '商品1', price: 100 }, { id: 2, name: '商品2', price: 200 }, { id: 3, name: '商品3', price: 300 }, { id: 4, name: '商品4', price: 400 }, ] let cart = [] // 添加商品到购物车 function addToCart(id) { const product = products.find(p => p.id === id) if (product) { cart.push(product) // 更新购物车页面 const cartList = document.getElementById('cart') const item = document.createElement('li') item.innerHTML = `${product.name}(${product.price}元)<button onclick="removeFromCart(${product.id})">移除</button>` cartList.appendChild(item) // 更新总价 const totalPrice = document.getElementById('totalPrice') totalPrice.innerText = getTotalPrice() } else { alert('商品不存在') } } // 从购物车中移除商品 function removeFromCart(id) { const index = cart.findIndex(p => p.id === id) if (index !== -1) { cart.splice(index, 1) // 更新购物车页面 const cartList = document.getElementById('cart') cartList.removeChild(cartList.childNodes[index]) // 更新总价 const totalPrice = document.getElementById('totalPrice') totalPrice.innerText = getTotalPrice() } else { alert('购物车中不存在该商品') } } // 计算购物车总价 function getTotalPrice() { return cart.reduce((total, product) => total + product.price, 0) } </script> </body> </html> ``` 在这个示例中,我们首先定义了一个商品列表和一个购物车数组,然后在页面中显示了商品列表和购物车。每个商品都有一个“添加到购物车”按钮,点击后调用`addToCart`函数将该商品添加到购物车中。购物车中的每个商品都有一个“移除”按钮,点击后调用`removeFromCart`函数将该商品从购物车中移除。同时,页面上会显示购物车中的商品列表和总价,这些数据会在添加或移除商品时动态更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值