booystrap和jquery实现购物车

本文介绍了一个基于HTML、CSS和JavaScript的购物车功能实现方案。详细展示了如何通过jQuery和原生JavaScript来实现商品的选择、数量增减及删除等功能,并保持购物车状态的一致性和实时性。

代码片段

// each方法得到的是HTML元素
  $(".store-checkbox").each((i, storeCheckboxE) => {
      if (storeCheckboxE.checked != target.checked) {
      // js触发点击事件
          $(storeCheckboxE).trigger("click");
      }
  });
// 可以通过创建数组的方式使用数组的api
[".subtract", ".add"].forEach((selector) => {
    if ($inputE.val() == limit) {
    // 原生js操纵class
        numE.querySelector(selector).classList.add("disabled");
    } else {
        var subtractE = numE.querySelector(selector);
        if (subtractE.className.indexOf("disabled") != -1) {
            subtractE.classList.remove("disabled");
        }
    }
    limit = "99999999";
});

// on方法传递的是事件
 $(".commodity-delete").on("click", function ({
     target
 }) {
     $commodity = $(target).parents(".commodity");
     if ($commodity.siblings(".commodity").length != 0) {
         $commodity.remove();
     } else {
         $commodity.parens(".store").remove();
     }
 });
// textContent可以获取该元素内文本
 var itemAmt = commodityE.querySelector(".commodity-amt").textContent;

源码

<!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>
    <link rel="stylesheet" href="../css/bootstrap.css" />
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
</head>
<style>
    .img {
        height: 80px;
        width: 80px;
    }

    .img img {
        width: 100%;
        height: 100%;
    }

    .num {
        height: 38px;
    }

    .num button {
        border: 1px solid #e2e6ea;
    }

    .btn.disabled {
        color: #e2e6ea;
        background: #81868a2e;
        cursor: not-allowed;
        border: 1px solid #bdc4cb;
    }
</style>

<body>
    <div class="jumbotron text-center">
        <h1>购物车</h1>
    </div>
    <div class="container">
        <div class="top row">
            <div class="col-2">车内商品(<span class="cart-commodity-num">5</span></div>
            <div class="col-4 offset-6">
                总价(不含运费):¥<span class="amount">0.00</span>
                <button class="btn btn-primary">结算</button>
            </div>
        </div>
        <div class="cart-head row">
            <div class="col-6">
                <div class="custom-control custom-checkbox constom-control-inline">
                    <input type="checkbox" name="checkAll" id="checkAll" class="custom-control-input checkAll" />
                    <label for="checkAll" class="custom-control-label">全选</label>
                </div>
            </div>
            <div class="col-1">单价</div>
            <div class="col-1">数量</div>
            <div class="col-2">金额</div>
            <div class="col-1">操作</div>
        </div>
        <div class="store">
            <div class="row">
                <div class="col-6">
                    <div class="custom-control custom-checkbox constom-control-inline">
                        <input type="checkbox" id="store-1" class="store-checkbox custom-control-input" />
                        <label for="store-1" class="store-name custom-control-label">店铺:小约翰杰克店
                        </label>
                    </div>
                </div>
            </div>
            <div class="row bg-light m-3 commodity">
                <div class="col-6 row m-0">
                    <div class="col-1">
                        <div class="custom-control custom-checkbox constom-control-inline">
                            <input type="checkbox" id="commodity-1" class="custom-control-input commodity-checkbox" />
                            <label for="commodity-1" class="custom-control-label cursor">
                            </label>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="img">
                            <img src="./img/shampoo-god.png" alt="" />
                        </div>
                    </div>
                    <div class="col-7">
                        【国庆价】God男士古龙洗发水控油去屑持久留香正品官方品牌旗舰产品
                    </div>
                </div>
                <div class="col-1 price">322.00</div>
                <div class="col-2 input-group num">
                    <div class="input-group-prepend">
                        <button class="btn btn-light subtract disabled">-</button>
                    </div>
                    <input type="text" class="form-control num-input text-center" value="1" />
                    <div class="input-group-append">
                        <button class="btn btn-light add">+</button>
                    </div>
                </div>
                <div class="col-2 commodity-amt">322.00</div>
                <div class="col-1 commodity-delete">删除</div>
            </div>
            <div class="row bg-light m-3 commodity">
                <div class="col-6 row m-0">
                    <div class="col-1">
                        <div class="custom-control custom-checkbox constom-control-inline">
                            <input type="checkbox" id="commodity-1" class="custom-control-input commodity-checkbox" />
                            <label for="commodity-1" class="custom-control-label cursor">
                            </label>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="img">
                            <img src="./img/shampoo-god.png" alt="" />
                        </div>
                    </div>
                    <div class="col-7">
                        【国庆价】God男士古龙洗发水控油去屑持久留香正品官方品牌旗舰产品
                    </div>
                </div>
                <div class="col-1 price">322.00</div>
                <div class="col-2 input-group num">
                    <div class="input-group-prepend">
                        <button class="btn btn-light subtract disabled">-</button>
                    </div>
                    <input type="text" class="form-control num-input text-center" value="1" />
                    <div class="input-group-append">
                        <button class="btn btn-light add">+</button>
                    </div>
                </div>
                <div class="col-2 commodity-amt">322.00</div>
                <div class="col-1 commodity-delete">删除</div>
            </div>
        </div>
        <div class="cart-footer row">
            <div class="col-6">
                <div class="custom-control custom-checkbox constom-control-inline">
                    <input type="checkbox" id="checkAll-footer" class="custom-control-input checkAll" />
                    <label for="checkAll-footer" class="custom-control-label">全选</label>
                </div>
            </div>
            <div class="col-2">
                已选商品<span class="commodity-selected-num"></span></div>
            <div class="col-4">
                总价(不含运费):¥<span class="amount">0.00</span>
                <button class="btn btn-primary">结算</button>
            </div>
        </div>
    </div>
</body>

<script>
    loadData();
    function getData() {
        var store = {
            name: "小约翰杰克",
            commoditys: [{
                id: "0",
                img: "./img/shampoo-god.png",
                discribe: "【国庆价】God男士古龙洗发水控油去屑持久留香正品官方品牌旗舰产品",
                price: "32.00",
                num: "1",
            }, ],
        };
        var data = [];
        for (let i = 0; i < 3; i++) {
            store = JSON.parse(JSON.stringify(store));
            var commoditys = [];
            for (let i = 0; i < 3; i++) {
                let commodity = JSON.parse(JSON.stringify(store.commoditys[0]));
                commodity.id = Math.random() // 使用随机数保证商品id唯一,模拟真实环境
                commoditys.push(commodity);
            }
            store.commoditys = commoditys;
            data.push(store);
        }
        return data;
    }

    // 将数据加载进购物车,更新车内商品数
    function loadData() {
        var num = 0; //车内商品数
        var data = getData();
        // 得到商品和店铺元素
        $storeTE = $(".store"); // 店铺元素模板
        $commodityTE = $storeTE.find('.commodity');

        // 删除模板代码
        $storeTE.find('.commodity').remove();
        $(".store").remove();

        var html = "";
        data.forEach((store, i) => {
            // 生成新的店铺元素,防止污染
            $storeE = $storeTE.clone();
            // 更改店铺名
            $storeE.find(".store-name").text(store.name + (i + 1));
            // 更改店铺复选框id和对应的labelfor属性
            var storeId = 'store-' + i;
            $storeE.find('.store-checkbox').attr({
                id: storeId
            })
            $storeE.find('.store-checkbox').siblings('label').attr({
                for: storeId
            })
            // 往店铺中装填商品,选项框和label必须是同辈元素
            store.commoditys.forEach((commodity, i) => {
                num++;// 车内商品数
                // 生成新的商品元素,防止污染
                $commodityE = $commodityTE.clone();
                // 更改商品复选框id和对应的label中for属性
                $commodityE.find('.commodity-checkbox').attr({
                    id: commodity.id
                })
                $commodityE.find('.commodity-checkbox').siblings('label').attr({
                    for: commodity.id
                });

                // 填入商品数据
                $commodityE.find('img').attr('src', commodity.img);
                $commodityE.find('.num input').text(commodity.num);
                $commodityE.find('.discribe').text(commodity.discribe);
                $commodityE.find('.price').text(commodity.price);
                $commodityE.find('.commodity-amt').text((parseFloat(commodity.price) *
                    parseFloat(commodity.num)).toFixed(2));
                // 将商品插入店铺
                $storeE.append($commodityE.get(0).outerHTML);
            })
            $(".cart-footer").before($storeE.clone());
            $(".cart-commodity-num").text(num);
        });

    }

    // 勾选和取消单个商品
    $(".commodity-checkbox").each(function (i, e) {
        $(e).on("click", function () {
            doFlush();     
        });
    });

    // 勾选和取消店铺的所有商品
    $(".store-checkbox").each(function (i, e) {
        $(e).on("click", () => {
            $(e)
                .parents(".store")
                .find(".commodity-checkbox")
                .each(function (i, checkboxE) {
                    if (e.checked != checkboxE.checked) {
                        $(checkboxE).trigger("click");
                    }
                });
        });
    });

    // 勾选和取消全选
    $(".checkAll").click(({
        target
    }) => {
        // 同步两个全选复选框
        $('.checkAll').each((i,e)=>{
            if(e.checked != target.checked){
                e.checked = target.checked
            }
        })
        $(".store-checkbox").each((i, storeCheckboxE) => {
            if (storeCheckboxE.checked != target.checked) {
                $(storeCheckboxE).trigger("click");
            }
        });
    });

    // 更改购买数量
    $(".num").each(function (i, numE) {
        var $inputE = $(numE).find(".num-input");

        // 数量改变时改变该商品总价
        var price = $(numE).parents(".commodity").find(".price").text();
        $inputE.change((e) => {
            var value = e.target.value;
            value = value.replace(/^[0]/, ""); // 删除开头的0
            value = value.replace(/[^\d]/g, ""); // 删除非数字
            // 最小只能1
            if (value < 1 || !value) {
                value = 1;
            } // 最大只能买99999999件商品
            value = value > 99999999 ? 99999999 : value;
            result = value * parseFloat(price);
            $inputE.parents(".commodity").find(".commodity-amt").text(result.toFixed(2));
            $inputE.val(value);
            // 刷新总价
            doFlush();

            // 设置特殊值时按钮样式
            var limit = "1";
            [".subtract", ".add"].forEach((selector) => {
                if ($inputE.val() == limit) {
                    numE.querySelector(selector).classList.add("disabled");
                } else {
                    var subtractE = numE.querySelector(selector);
                    if (subtractE.className.indexOf("disabled") != -1) {
                        subtractE.classList.remove("disabled");
                    }
                }
                limit = "99999999";
            });
        });

        // 设置点击增加或减小按钮时,触发改变购买数量输入框值事件,总价跟着改变
        numE.onclick = ({
            target
        }) => {
            num = target.textContent == "+" ? 1 : -1;
            $inputE.val(parseInt($inputE.val()) + num);
            $inputE.trigger("change");
        };
    });

    // 删除单个商品
    $(".commodity-delete").on("click", function ({
        target
    }) {
        $commodity = $(target).parents(".commodity");
        if ($commodity.siblings(".commodity").length != 0) {
            $commodity.remove();
        } else {
            $commodity.parens(".store").remove();
        }
    });

    // 刷新总价,已选商品数
    function doFlush() {
        var amt = 0;
        var num = 0; //被选商品数
        $(".commodity").each((i, commodityE) => {
            var isChecked = commodityE.querySelector(".commodity-checkbox").checked;
            if (isChecked) {
                var itemAmt = commodityE.querySelector(".commodity-amt").textContent;
                amt += parseFloat(itemAmt);
                num++;
            }
        });
        $(".amount").text(amt.toFixed(2));
        $('.commodity-selected-num').text(num);
    }
</script>

</html>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值