简单实现购物车相同物品累加

简单实现购物车相同物品累加

遇到过这样的一个需求,如何在商城的购物车里面自动累计相同的商品,而不是重新创建一个新的商品项,商品列表不需要使用+-号来控制商品的数量。网上找不到类似的方案,所以就自己写了一个,虽然不是最佳的解决方案。有更好的建议或者写法,请联系我,谢谢。

index.html

  1 <html lang="zh">
  2 
  3 <head>
  4     <meta charset="utf-8">
  5     <meta http-equiv="X-UA-Compatible" content="ie=edge">
  6     <meta name="renderer" content="webkit">
  7     <title>礼品商城</title>
  8     <style>
  9         * {
 10             -webkit-box-sizing: border-box;
 11             -moz-box-sizing: border-box;
 12             box-sizing: border-box;
 13             margin: 0;
 14             padding: 0;
 15         }
 16         
 17         html,
 18         body {
 19             overflow-x: hidden;
 20             overflow-y: auto;
 21         }
 22         
 23         .good-list__bd {
 24             overflow: hidden;
 25             margin-top: 1%;
 26             margin-left: 1%;
 27             padding-bottom: 4%;
 28         }
 29         
 30         .good-list__item {
 31             float: left;
 32             overflow: hidden;
 33             width: 32.33333%;
 34             margin-right: 1%;
 35             margin-bottom: 1%;
 36             text-align: center;
 37             border: 1px solid #f5f5f5;
 38         }
 39         
 40         .good-list__image {
 41             width: 100%;
 42             height: 250px;
 43         }
 44         
 45         .good-list__name {
 46             font-size: 20px;
 47             line-height: 42px;
 48             overflow: hidden;
 49             width: 100%;
 50             height: 42px;
 51             margin-bottom: 8px;
 52         }
 53         
 54         .good-list__btn {
 55             font-size: 15px;
 56             line-height: normal;
 57             display: block;
 58             width: 120px;
 59             height: 40px;
 60             margin: 15px auto;
 61             color: #fff;
 62             border: none;
 63             border-radius: 5px;
 64             background-color: #f00;
 65             -ms-flex-item-align: auto;
 66             align-self: auto;
 67         }
 68         
 69         .good-car {
 70             position: fixed;
 71             z-index: 999;
 72             bottom: 0;
 73             width: 100%;
 74             height: 60px;
 75             background: #000;
 76         }
 77         
 78         .good-car-btn {
 79             font-size: 24px;
 80             line-height: 60px;
 81             float: right;
 82             width: 10%;
 83             color: #fff;
 84         }
 85         
 86         .good-car-btn,
 87         .good-icon__round {
 88             height: 60px;
 89             text-align: center;
 90             background: #f40;
 91         }
 92         
 93         .good-icon__round {
 94             position: absolute;
 95             top: -10px;
 96             left: 10px;
 97             width: 60px;
 98             border-radius: 50%;
 99         }
100         
101         .good-icon__point {
102             font-size: .1rem;
103             position: absolute;
104             top: 1px;
105             right: 0;
106             display: block;
107             width: 15px;
108             height: 15px;
109             color: #fff;
110             border-radius: 50%;
111             background: red;
112         }
113         
114         .good-car__name {
115             display: inline-block;
116             vertical-align: top;
117         }
118         
119         .good-icon {
120             display: block;
121             width: 40px;
122             height: 40px;
123             margin: 10px auto;
124         }
125         
126         .good-car__bd {
127             position: absolute;
128             bottom: 60px;
129             display: none;
130             width: 100%;
131             border-top: 1px solid #f00;
132             background: #fff;
133         }
134         
135         .good-car__img {
136             width: 50px;
137             height: 50px;
138         }
139         
140         .good-car__item {
141             padding: 12px;
142         }
143         
144         .good-car__count {
145             float: right;
146             margin-right: 20px;
147         }
148     </style>
149 </head>
150 
151 <body>
152     <div class="wrap">
153         <!-- 商品列表 -->
154         <div class="good-list">
155             <ul class="good-list__bd"></ul>
156         </div>
157         <!-- 购物车 -->
158         <div class="good-car">
159             <ul class="good-car__bd">
160             </ul>
161             <div class="good-icon__round" data-shop="1">
162                 <span class="good-icon__point">0</span>
163                 <img class="good-icon" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHlSURBVFhH7de9SxxBGMfx06AiRgQrtUij9rYBC18qSUARDOJ/IKQR/R+sU0QFQex8acVCAkYsxcpCsRDFTtOkMlEU/T5wDzwM4+3d3szuifeDD8ety8zjzsPMXoE8J+hCrvEVZU0j1/iKslaQa6Y8dqAFnqLmIstqn2LufehGCrIF5t6HvpxBC8y9D32RorTAeh+myZvrw2W5UGup92G1cfvwANsZmkRibB9m7TMSY/swSzdoRGLcPtyDbzlCeIDOs4qyktV+2A87zwTKThbn8jx0jv/4iLJj+1CKjZF96By7cqGSxN4PO/EIHX8WFSV2H87Ajv8JFUeOOh0gdB9uQsc+kQtpEqsPm/AXOvYiUiVWH47AjjuIVInVhz+gY8rp8QGpY/tQfpr6frJW6hI65jqqSuxzWQquKm4fhiTncAeqituHIf3C+0sDBjBe/JTvpdKKYXxFj1yImT4cwy7TEXrhi/TvH+i9T/iJZgRPO65gi1MXaIPNKOzLgLWE4PkO32RK/m5zCN99QgrvRtDIhuqbTLkb7j/47lNfEDSyLL6JlLtstvd8hhA08h/7JlJjsCn1xG/RguDZgm/CDbiRLeUa7r3Sf98QJfLWsYBz3Bc/5/Da24gUuQZ5Ynf4DdkTS6RQeAGh7aMfK2AISAAAAABJRU5ErkJggg==">
164             </div>
165             <div class="good-car-btn">去结算</div>
166         </div>
167     </div>
168     <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
169     <script type="text/javascript" src="./index.js"></script>
170 </body>
171 
172 </html>

index.js

var getlistGoodJsonHtml = "", //商品列表
    listHtml = "", //购物车商品列表
    shopArr = [], //购物车数组
    num = 1; //商品数量

$(function() {

    var listGoodJson = {
        "goods": [{
                "id": "1",
                "name": "商品1",
                "img": "http://via.placeholder.com/500x500"
            }, {
                "id": "2",
                "name": "商品2",
                "img": "http://via.placeholder.com/500x500"
            }, {
                "id": "3",
                "name": "商品3",
                "img": "http://via.placeholder.com/500x500"
            }, {
                "id": "4",
                "name": "商品4",
                "img": "http://via.placeholder.com/500x500"
            }, {
                "id": "5",
                "name": "商品5",
                "img": "http://via.placeholder.com/500x500"
            }, {
                "id": "6",
                "name": "商品6",
                "img": "http://via.placeholder.com/500x500"
            }

        ]
    }

    //初始化商品列表
    initGoodList();

    function initGoodList() {
        var getlistGoodJson = listGoodJson.goods;
        for (var x in getlistGoodJson) {
            getlistGoodJsonHtml += "<li class='good-list__item' id='" + getlistGoodJson[x].id + "'><img class='good-list__image' src='" + getlistGoodJson[x].img + "'><p class='good-list__name'>" + getlistGoodJson[x].name + "</p><button class='good-list__btn'>兑换</button></li>"
        }
        $(".good-list__bd").append(getlistGoodJsonHtml);
    }

    //点击元素
    $(".good-list__bd").on("click", ".good-list__btn", function(e) {

        //获取点击商品的父节点            
        var parent = $(this)[0].parentNode;

        //获取点击的商品信息
        var goodID = parent.id;
        var goodPicUrl = parent.getElementsByClassName("good-list__image")[0].currentSrc;
        var goodName = parent.getElementsByClassName("good-list__name")[0].childNodes[0].wholeText;

        var goodsObj = {
            goodID: goodID,
            goodPicUrl: goodPicUrl,
            goodName: goodName
        }

        //转化成字符串
        var goodsObjStr = JSON.stringify(goodsObj);
        var shopArrStr = JSON.stringify(shopArr);

        //判断商品是否添加在购物车列表
        if (shopArrStr.indexOf(goodsObjStr) > 0) {
            // 在已有的购物车商品列表添加数量
            listHtml = "";
            num = parseInt($("#good" + goodsObj.goodID).text()) + 1;
            $("#good" + goodsObj.goodID).text(num);
        } else {
            // 新建商品item
            shopArr.push(goodsObj);
            listHtml = "<li class='good-car__item'><img class='good-car__img' src='" + goodsObj.goodPicUrl + "'/> <span class='good-car__name' >" + goodsObj.goodName + "</span><div class='good-car__count'>数量:<span class='good-car__num' id='good" + goodsObj.goodID + "'>1</span></div></li>";
        }
        $(".good-icon__point").text(shopArr.length);
        $(".good-car__bd").append(listHtml)
    });

    //购物车隐藏显示
    $(".good-icon__round").on("click", function() {
        if ($(".good-icon__round").attr("data-shop") === '1') {
            $(".good-car__bd").show();
            $(".good-icon__round").attr("data-shop", "0");
        } else {
            $(".good-car__bd").hide();
            $(".good-icon__round").attr("data-shop", "1");
        }
    });

})