2021-06-08 购物车

效果:

在商品选购列表中选中的商品可以在购物车页面中同步看到,购物车有添加增减商品数量和删除商品功能

代码:

  商品列表页:list.html

    html:
<h1>这是商品列表,去<a href="cart.html">购物车</a></h1>
<div id="cont">
    <p>卖完了,等待上架中...</p>
    <!-- <div class="box">
        <img src="https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg" alt="">
        <p>3999.00</p>
        <p>OPPO K7x 双模5G 4800万四摄 5000mAh长续航 90Hz电竞屏  黑镜6GB+128GB 30W闪充全网通</p>
        <span>加入购物车</span>
    </div> -->
</div>
    css:
#cont {width: 1000px;border: solid;overflow: hidden;margin: 0 auto;}
#cont .box {width: 250px;text-align: center;border: solid;box-sizing: border-box;float: left;}
.box img {width: 200px;}
.box p {margin: 10px 0;}
.box p:nth-child(3) {height: 40px;line-height: 20px;overflow: hidden;}
.box span {width: 100px;height: 40px;padding: 0 10px;margin: 10px auto;background: cyan;line-height: 40px;text-align: center;display: block;cursor: pointer;}
.box span:active {background: blue;color: #fff;}
    js:
引入 good.js文件
class List{
	constructor(){
		this.cont=document.getElementByid("cont");
		this.load();
		this.addEvent();
	}
	//拿数据
	load(){
		//数据获取
		ajax().then(data=>{
		//字符串->对象
		this.data=JSON.parse(data);
		//数据渲染的方法调用
		this.render();
		})
	}
	//渲染数据
	render(){
		//str接data中的数据
		let str='';
		this.data.forEach(val=>{
			str+=`<div class="box" index="${val.proId}">
					 <img src="${val.proImg}" alt="">
					 <p>${val.price}</p>
					 <p>${val.proName}</p>
					 <span class="btn">加入购物车</span>
				</div>`;
		});
		//cont中的文本内容设置为str
		this.cont.innerHTML=str;
	}
	//事件的添加
	addEvent(){
		//this后续会改变.设置一个that代表改变之前的this
		const that=this;
		this.cont.addEventListener("click",function(eve){
			if(eve.target.className=="btn"){
				//令点击事件的id=proId
				that.id=eve.target.parentNode.getAttibute("index");
				//存储数据:调用setData()方法
				that.setData();
			}
		});
	}

	//判断是否首次加入购物车,并根据不同状况进行不同处理
	setData(){
		//同一个数组去接本地存储的数据
		const arr=localStorage.getItem("proData")?JSON.parse(localStorage.getItem("proData")):[];
		
		//1.arr长度不为0:不是首次加入购物车
		if(arr.length>0){
		let i=0;
		/*数组some方法:找到数组中复合条件的一个元素就返回true并结束*/
		//onOff的布尔值取决于some方法的布尔值
		const onOff=arr.some((val,idx)=>{
			//记录true时的索引
			i=idx;
			//返回==表达式的结果
			return val.id=this.id;
		});

			//	1.1.onOff=true:购物车已经存在过这个商品
			if(onOff){
				arr[i].num++;
			}
			//	1.2.购物车新加入这个商品
			else{
				arr.push({
					id:this.id,
					num:1
				});
			}
		}
		//2.首次加入购物车
		else{
			arr.push({
				id:this.id,
				num:1
			});		
		}
	//本地存储中将处理后的arr赋为parData的属性值
	localStorage.setItem("proData",JSON.stringify(arr);
	}	
}
new List;

//异步拿取数据
function  ajax(){
	return new Promise(resolve=>{
		setTImeout(()=>{
			resolve(JSON.stringify(data));
		},500);
	});
}

  购物车页面:cart.html

    html:
<h1>这是购物车页面,<a href="list.html">继续购物</a></h1>
<table border="1" width="800" align="center">
    <thead>
        <tr>
            <th>图片</th>
            <th>名称</th>
            <th>单价</th>
            <th>数量</th>
            <th>总价</th>
            <th width=40>操作</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="6">购物车为空,<a href="./list.html">继续选购</a></td>
        </tr>
        <!-- <tr>
            <td><img src="" alt=""></td>
            <td>名称</td>
            <td>99.00</td>
            <td><input type="number" min="1" value="5"></td>
            <td>数量*单价</td>
            <td>删除</td>
        </tr> -->
    </tbody>
</table>
    css:
        img {width: 100px;}
    js:
class Cart{
	constructor(){
		this tbody=document.getElementById("tbody");
		this.load();
		this.addEvent();
	}
	load(){
		ajax({
			url:"dfhsla"
		}).then(data=>{
			this.data=JSON.parse(data);
			this.render();
		})
	}
	render(){
		this.localData=localStorage.getItem("proData")?JSON.parse(localStorage.getItem("proData")):[];
		if(this.localData.length<1) return;
		let str="";
		this.data.forEach(val1=>{
			this.localData.forEach(val2=>{
				if(val1.proId===val2.id){
					str+=`<tr index="${val2.id}>
           					 <td><img src="${val1.proImg}" alt=""></td>
           					 <td>${val1.proName}</td>
        				     <td>${val1.price}</td>
       					     <td><input type="number" min="1" value="${val2.num}"></td>
          					 <td>${val1.price*val2.num}</td>
            				 <td>删除</td>
       					 </tr>`;
				}
			})
		});
		this.tbody.innerHTML=str;
	}
	addEvent(){
		const that=this;
		this.tbody.addEventListener("click",function(e){
			if(e.target.className==="del"){
				that.id=e.target.parentNode.getAttribute("input");
				e.target.parentNode.remove();
				that.setData(i=>that.localData.splice(i,1));
			}
		})
		this.tbody.addEventListener("input",function(e){
			if(e.target.className==="set"){
				that.id=e.target.parentNode.parentNode.getAttribute("index");
				that.setData(i=>that.localData[i].num=e.target.value);				
			}
		})
	}
	setData(cb){
		let i=0;
		this.localData.some((val,idx)=>{
			i=idx;
			return val.id=this.id;
		})
		cb(i);
		localStorage.setItem("proData",JSON.stringify(this.localData));
	}
}
new Cart;
function ajax(){
	return new Promise((resolve)=>{
		setTimeout(function(){
			resolve(JSON.stringify(data));
		},500)
	});
}

  商品数据:good.js

var data=[
	    {
        "proId": "proId-50990677-a288-11eb-af86-375d9076f459",
        "proImg": "https://img12.360buyimg.com/n1/s450x450_jfs/t1/128286/7/2247/303790/5ec37cabEf2a27dc3/4dec5022f102a39b.jpg",
        "proName": "戴尔DELL灵越5000 14英寸酷睿i5轻薄笔记本电脑(十代i5-1035G1 8G 512G MX230 2G独显)银",
        "brand": "DELL",
        "logo": "http://img30.360buyimg.com/popshop/jfs/t1114/95/265737457/7715/95b70982/550fb619Nc0269ee4.jpg",
        "type": "电脑",
        "price": 4299,
        "sales": 10,
        "stock": 155,
        "score": 4.8,
        "discount": 8,
        "describe": "商品名称:戴尔灵越5000商品编号:100006546527商品毛重:2.5kg商品产地:中国大陆显卡类别:入门级游戏独立显卡优选服务:两年质保厚度:15.1mm—18.0mm特性:PCIE高速固态硬盘屏幕尺寸:14-14.9英寸系列:戴尔 - Inspiron显存容量:2GB分类:轻薄笔记本裸机重量:1.5-2kg处理器:Intel i5屏幕刷新率:其他待机时长:5-7小时内存容量:8G显卡型号:MX230硬盘容量:512G SSD系统:Windows 10颜色:银色",
        "time": 1618999191639
    },
    {
	/*若干个与上面相同格式的商品数据形成一个data数组*/
	}
];	
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端OnTheRun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值