利用localStorage实现购物车功能

1 篇文章 0 订阅
1 篇文章 0 订阅

准备好json数据

[
  {
    "id": 1,
    "src": "http://img12.360buyimg.com/n7/jfs/t1/4136/40/6201/250287/5ba1f333E745fc8b9/b34c5ccc4c4fd548.jpg",
    "price": 1099,
    "name": "小米8青春版 镜面渐变AI双摄 6GB+64GB 深空灰 全网通4G"
  },
  {
    "id": 2,
    "src": "https://img11.360buyimg.com/n7/jfs/t2278/69/129833021/96430/df8863b1/55f0e861Nf585867f.jpg",
    "price": 3599.00,
    "name": "Apple iPhone 6s Plus (A1699) 128G 银色 移动联通电信4G手机"
  },
  {
    "id": 3,
    "src": "https://img10.360buyimg.com/n7/jfs/t3985/131/486256904/433682/1d9fc4d0/584fcc81N1a31a2c5.jpg",
    "price": 3059.00,
    "name": "华为 Mate 9 Pro 6GB+128GB版 银钻灰 移动联通电信4G手机 双卡双待"
  },
  {
    "id": 4,
    "src": "https://img10.360buyimg.com/n7/jfs/t10729/149/1744838942/273871/5b00d30c/59e5bd89Ndc046ccd.jpg",
    "price": 1099.00,
    "name": "荣耀 畅玩7X 4GB+32GB 全网通4G全面屏手机 标配版 幻夜黑"
  },
  {
    "id": 5,
    "src": "https://img10.360buyimg.com/n7/jfs/t3985/131/486256904/433682/1d9fc4d0/584fcc81N1a31a2c5.jpg",
    "price": 3059.00,
    "name": "华为 Mate 9 Pro 6GB+128GB版 银钻灰 移动联通电信4G手机 双卡双待"
  },
  {
    "id": 6,
    "src": "https://img10.360buyimg.com/n7/jfs/t10729/149/1744838942/273871/5b00d30c/59e5bd89Ndc046ccd.jpg",
    "price": 1099.00,
    "name": "荣耀 畅玩7X 4GB+32GB 全网通4G全面屏手机 标配版 幻夜黑"
  },
  {
    "id": 7,
    "src": "https://img10.360buyimg.com/n7/jfs/t3985/131/486256904/433682/1d9fc4d0/584fcc81N1a31a2c5.jpg",
    "price": 3059.00,
    "name": "华为 Mate 9 Pro 6GB+128GB版 银钻灰 移动联通电信4G手机 双卡双待"
  },
  {
    "id": 8,
    "src": "https://img10.360buyimg.com/n7/jfs/t10729/149/1744838942/273871/5b00d30c/59e5bd89Ndc046ccd.jpg",
    "price": 1099.00,
    "name": "荣耀 畅玩7X 4GB+32GB 全网通4G全面屏手机 标配版 幻夜黑"
  }
]

index.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>
    <link rel="stylesheet" href="css/goodsLst.css">
</head>

<body>
    <div id="cont"></div>
    <script src="./js/ajax.js"></script>
    <script src="./js/index.js"></script>
</body>

</html>

index.js

 // 1 构造json数据,每一个json中就是一个商品
 ajax('get', './json/goods.json').then(data => {
    // console.log(JSON.parse(data));
    let html = '';
    JSON.parse(data).forEach(goods => {
        // console.log(goods);
        html +=
            `<div class="box">
                <img src="${goods.src}" alt="">
                <p>${goods.name}</p>
                <span class="goods_item_price" data-price-id="100004222715" style="">¥${goods.price}</span>
                <a href="#none" id="InitCartUrl" class="btn-special1 btn-lg" onclick="addCart(${goods.id},'${goods.name}','${goods.src}','${goods.price}',1)">加入购物车</a>
            </div>`;
    });
    document.querySelector('#cont').innerHTML = html;
})

function addCart(id, name, src, price, num) {
    let cartGoods = localStorage.getItem('cart');
    if (cartGoods) {
        cartGoods = JSON.parse(cartGoods);
        var flag = false;
        cartGoods.forEach(v => {
            if (v.id == id) {
                v.num = v.num - 0 + (num - 0);
                flag = true;
            }
        })
        if (!flag) {
            cartGoods.push({
                id,
                name,
                src,
                price,
                num
            })
        }
        localStorage.setItem('cart', JSON.stringify(cartGoods));
    } else {
        let temp = {
            id,
            name,
            src,
            price,
            num
        }
        let goodsArr = [temp]
        localStorage.setItem('cart', JSON.stringify(goodsArr));
    }
}

ajax.js

function ajax(method, url, data) {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        if (method == 'post') {
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
            if (data) {
                xhr.send(data);
            } else {
                xhr.send();
            }
        } else {
            xhr.send();
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(xhr.response);
                } else {
                    reject('error');
                }
            }
        }
    })
}

cart.js

class Car {
    constructor() {
        this.getLocalStorage();
        this.select();
        this.changeNum();
        this.totalNum();
        this.delObj();
    }
    //1.渲染数据
    getLocalStorage() {
        let goodsList = localStorage.getItem('cart');
        goodsList = JSON.parse(goodsList);
        let html = '';
        goodsList.forEach(k => {
            html += `
            <tr>
                <td class="checkbox">
                    <input class="check-one check" type="checkbox" />
                </td>
                <td class="goods">
                    <img src="${k.src}" alt="" />
                    <span>${k.name}</span>
                </td>
                <td class="price">${k.price}</td>
                <td class="count">
                    <span class="reduce">-</span>
                    <input class="count-input" type="text" value="${k.num}" />
                    <span class="add">+</span>
                </td>
                <td class="subtotal">${k.price*k.num}</td>
                <td class="operation">
                    <span class="delete">删除</span>
                </td>
            </tr>`
        });
        document.querySelector('tbody').innerHTML = html;
    }
    //2.单选和全选按钮
    select() {
        var oneChecked = document.querySelectorAll('.check-one');
        var allChecked = document.querySelectorAll('.check-all');
        //全选
        allChecked[0].addEventListener('click', this.selectAll.bind(this, 1))
        allChecked[1].addEventListener('click', this.selectAll.bind(this, 0))
        //单选
        oneChecked.forEach(k => {
            k.addEventListener('click', this.selectOne.bind(this))
        })
    }
    //2.1全选功能
    selectAll(index, e) {
        var oneChecked = document.querySelectorAll('.check-one');
        var allChecked = document.querySelectorAll('.check-all');
        let checkInfo = e.target.checked;
        allChecked[index].checked = checkInfo;
        oneChecked.forEach(k => {
            k.checked = checkInfo;
        })
        this.totalNum();
    }
    //2.2单选功能
    selectOne(e) {
        var that = this;
        let flag = true;
        var allChecked = document.querySelectorAll('.check-all');
        var oneChecked = document.querySelectorAll('.check-one');
        oneChecked.forEach(k => {
            if (k.checked == false) {
                flag = false;
            }
            that.totalNum();
        })
        if (flag) {
            allChecked.forEach(k => {
                k.checked = true;
            })
        } else {
            allChecked.forEach(k => {
                k.checked = false;
            })
        }
    }
    //3.改变商品数量和小计
    changeNum() {
        var that = this;
        var counts = document.querySelectorAll('.count');
        counts.forEach((count, k) => {
            count.parentNode.setAttribute('index', k);
            count.addEventListener('click', function (e) {
                let tag = e.target;
                let price = this.previousElementSibling.innerHTML;
                let total = this.nextElementSibling;
                let index = this.parentNode.getAttribute('index');
                let status = localStorage.getItem('cart');
                status = JSON.parse(status);
                let countIpt = this.querySelector('.count-input');
                if (tag.className == 'add') {
                    countIpt.value = countIpt.value - 0 + 1;
                } else if (tag.className == 'reduce') {
                    countIpt.value = countIpt.value - 1;
                    if (countIpt.value < 1) {
                        countIpt.value = 1;
                    }
                }
                status[index].num = countIpt.value;
                localStorage.setItem('cart', JSON.stringify(status))
                total.innerHTML = price * countIpt.value;
                that.totalNum();
            })
        })
    }
    //4.获取总的商品数量和价格
    totalNum() {
        var countIpt = document.querySelectorAll('.count-input');
        var subTotal = document.querySelectorAll('.subtotal');
        var numTotal = document.querySelector('#selectedTotal');
        var priceTotal = document.querySelector('#priceTotal');
        numTotal.innerHTML = 0;
        priceTotal.innerHTML = 0;
        countIpt.forEach(k => {
            if (k.parentNode.parentNode.children[0].children[0].checked == true) {
                numTotal.innerHTML = numTotal.innerHTML - 0 + (k.value - 0);
            }
        })
        subTotal.forEach(k => {
            if (k.parentNode.children[0].children[0].checked == true) {
                priceTotal.innerHTML = priceTotal.innerHTML - 0 + (k.innerHTML - 0);
            }
        })
    }
    //5.删除
    delObj() {
        let dels = document.querySelectorAll('.operation .delete');
        let allDel = document.querySelector('#deleteAll');
        let that = this;
        dels.forEach(del => {
            del.addEventListener('click', function () {
                layer.confirm('确认删除?', {
                    btn: ['确认', '关闭'] //按钮
                }, function (index) {
                    let i = this.parentNode.parentNode.getAttribute('index');
                    let status = localStorage.getItem('cart')
                    status = JSON.parse(status);
                    status.splice(i, 1);
                    localStorage.setItem('cart', JSON.stringify(status));
                    this.parentNode.parentNode.remove();
                    that.totalNum();
                    layer.close(index);
                }.bind(this))
            })
        })
        allDel.addEventListener('click', function () {
            let flag = this.previousElementSibling.children[0].checked;
            var tr = document.querySelectorAll('tbody tr')
            if (flag == true) {
                let status = localStorage.getItem('cart')
                status = JSON.parse(status);
                status.splice(0, status.length);
                localStorage.setItem('cart', JSON.stringify(status));
                tr.forEach(k => {
                    k.remove();
                })
                this.previousElementSibling.children[0].checked = false;
                document.querySelector('thead .check').checked = false;
                that.totalNum();
            }
        })
    }
}
new Car();

cart.css

* {
    margin: 0;
    padding: 0;
}
a {
    color: #666;
    text-decoration: none;
}
body {
    padding: 20px;
    color: #666;
}
.fl{
    float: left;
}
.fr {
    float: right;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
    border: 0;
    text-align: center;
    width: 937px;
}
th, td {
    border: 1px solid #CADEFF;
}
th {
    background: #e2f2ff;
    border-top: 3px solid #a7cbff;
    height: 30px;
}
td {
    padding: 10px;
    color: #444;
}
tbody tr:hover {
    background: RGB(238,246,255);
}
.checkbox {
    width: 60px;
}
.goods {
    width: 300px;
}
.goods span {
    width: 180px;
    margin-top: 20px;
    text-align: left;
    float: left;
}
.price {
    width: 130px;
}
.count {
    width: 90px;
}
.count .add, .count input, .count .reduce {
    float: left;
    margin-right: -1px;
    position: relative;
    z-index: 0;
}
.count .add, .count .reduce {
    height: 23px;
    width: 17px;
    border: 1px solid #e5e5e5;
    background: #f0f0f0;
    text-align: center;
    line-height: 23px;
    color: #444;
}
.count .add:hover, .count .reduce:hover {
    color: #f50;
    z-index: 3;
    border-color: #f60;
    cursor: pointer;
}
.count input {
    width: 50px;
    height: 15px;
    line-height: 15px;
    border: 1px solid #aaa;
    color: #343434;
    text-align: center;
    padding: 4px 0;
    background-color: #fff;
    z-index: 2;
}
.subtotal {
    width: 150px;
    color: red;
    font-weight: bold;
}
.operation {
    width: 80px;
}
.operation span:hover, a:hover {
    cursor: pointer;
    color: red;
    text-decoration: underline;
}
img {
    width: 100px;
    height: 80px;
    /*border: 1px solid #ccc;*/
    margin-right: 10px;
    float: left;
}

.foot {
    width: 935px;
    margin-top: 10px;
    color: #666;
    height: 48px;
    border: 1px solid #c8c8c8;
    background-color: #eaeaea;
    background-image:linear-gradient(RGB(241,241,241),RGB(226,226,226));
    position: relative;
    z-index: 8;
}
.foot div, .foot a {
    line-height: 48px;
    height: 48px;
}
.foot .select-all {
    width: 100px;
    height: 48px;
    line-height: 48px;
    padding-left: 5px;
    color: #666;
}
.foot .closing {
    border-left: 1px solid #c8c8c8;
    width: 100px;
    text-align: center;
    color: #000;
    font-weight: bold;
    background: RGB(238,238,238);
    cursor: pointer;
}
.foot .total{
    margin: 0 20px;
    cursor: pointer;
}
.foot  #priceTotal, .foot #selectedTotal {
    color: red;
    font-family: "Microsoft Yahei";
    font-weight: bold;
}
.foot .selected {
    cursor: pointer;
}
.foot .selected .arrow {
    position: relative;
    top:-3px;
    margin-left: 3px;
}
.foot .selected .down {
    position: relative;
    top:3px;
    display: none;
}
 .show .selected .down {
    display: inline;
}
 .show .selected .up {
    display: none;
}
.foot .selected:hover .arrow {
    color: red;
}
.foot .selected-view {
    width: 935px;
    border: 1px solid #c8c8c8;
    position: absolute;
    height: auto;
    background: #ffffff;
    z-index: 9;
    bottom: 48px;
    left: -1px;
    display:none;
}
.show .selected-view {
    display: block;
}
.foot .selected-view div{
    height: auto;
}
.foot .selected-view .arrow {
    font-size: 16px;
    line-height: 100%;
    color:#c8c8c8;
    position: absolute;
    right: 330px;
    bottom: -9px;
}
.foot .selected-view .arrow span {
    color: #ffffff;
    position: absolute;
    left: 0px;
    bottom: 1px;
}
#selectedViewList {
    padding: 20px;
    margin-bottom: -20px;
}
#selectedViewList div{
    display: inline-block;
    position: relative;
    width: 100px;
    height: 80px;
    border: 1px solid #ccc;
    margin: 10px;
}
#selectedViewList div span {
    display: none;
    color: #ffffff;
    font-size: 12px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 60px;
    height: 18px;
    line-height: 18px;
    text-align: center;
    background: RGBA(0,0,0,.5);
    cursor: pointer;
}
#selectedViewList div:hover span {
    display: block;
}

goodsList.css

	* {
	    margin: 0;
	    padding: 0;
	}

	#cont {
	    width: 1000px;
	    overflow: hidden;
	    margin: 30px auto;


	}

	.box {
	    width: 250px;
	    border: 1px solid #f2f2f2;
	    box-sizing: border-box;
	    text-align: center;
	    float: left;
	}

	.box img {
	    width: 90%;
	    display: block;
	    margin: 10px auto;
	}

	.box span {
	    display: block;
	    color: red;
	}

	.box p {
	    height: 52px;
	    overflow: hidden;
	    font: 12px/150% tahoma, arial, Microsoft YaHei, Hiragino Sans GB, "\u5b8b\u4f53", sans-serif;
	    line-height: 26px;
	}

	.btn-lg {
	    height: 30px;
	    line-height: 30px;
	    padding: 0 26px;
	    font-size: 18px;
	    font-family: "microsoft yahei";
	    margin-bottom: 5px;
	}

	.btn-special1 {
	    font-weight: 700;
	}

	.btn-special1 {
	    background-color: #df3033;
	    color: #fff;
	}

	.btn-special1 {
	    display: inline-block;
	    text-align: center;
	    vertical-align: middle;
	    cursor: pointer;
	}

	a {
	    color: #666;
	    text-decoration: none;
	}

	.goods_item_price {
	    color: rgb(221, 69, 69);
	    margin: 0px 5px;
	}

点击加入购物车过后,可以再控制台Application下的localStorage中看到商品信息

 

 在购物车界面可以展示商品信息

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值