当前位置: 首页 > news >正文

基础购物车功能总结

今天是基础购物车功能的讲解。

整体是长这样的:

所具备的功能:

  1. 商品展示:以表格形式展示商品的名称、价格、数量和操作选项。
  2. 商品添加:用户点击 “添加” 按钮,输入商品名称、价格和数量,可以将新商品添加到购物车中。
  3. 商品编辑:可以对已经存在的商品进行编辑,修改商品的名称、价格和数量。
  4. 商品删除:用户可以删除不需要的商品。
  5. 总价和总数量计算:实时计算购物车中商品的总价和总数量,并在页面上显示。

我们的商品数据都是在json文件中保存的,所以我们要首先准备一个json文件,也就是肯定会用到ajax获取数据。

HTML 结构

<table cellspacing="0">
			<thead>
				<tr>
					<th>商品名称</th>
					<th>商品价格(单位为元)</th>
					<th>商品数量</th>
					<th>操作</th>
				</tr>
			</thead>
				<tbody>
					
				</tbody>
			<tfoot>
				<tr>
					<th>总价:</th>
					<td class="total_price">0</td>
					<th>总数量:</th>
					<td class="total_num">0</td>
				</tr>
			</tfoot>
		</table>
		<button onclick="display()">添加</button>
		<div class="add_box" style="width: 40%;">
			<input type="text" class="add_name" placeholder="请输入商品名称"/>
			<input type="text" class="add_price" placeholder="请输入商品价格"/>
			<input type="text" class="add_num" placeholder="请输入商品数量">
			<button class="add_ensure" onclick="ensure(1)">
				确定
			</button>
			<button class="add_cancel" onclick="cancel()">
				取消
			</button>
		</div>
		
		<div class="redact_box" style="width: 40%;">
			<input type="text" class="edit_name" placeholder="请输入商品名称"/>
			<input type="text" class="edut_price" placeholder="请输入商品价格"/>
			<input type="text" class="edit_num" placeholder="请输入商品数量">
			<button class="edit_ensure" onclick="ensure(2)">
				确定
			</button>
			<button class="edit_cancel" onclick="cancels()">
				取消
			</button>
		</div>
		
		<script src="js/shopingCar.js"></script>

这段 HTML 代码构建了购物车的基本结构,包括一个表格用于展示商品信息,两个隐藏的输入框组分别用于添加和编辑商品,以及相应的按钮用于触发操作。

CSS 样式

*{
				margin: 0;
				padding: 0;
			}
			body{
				padding-top: 10px;
				padding-left: 10px;
			}
			table{
				width: 40%;
				height: 100px;
				text-align: center;
				/* border: 1px solid black; */
			}
			thead{
				width: 40%;
				
			}
			th {
				padding: 8px 10px 8px 10px;
				border: 1px solid black;
			}
			
			td {
				padding: 8px 10px 8px 10px;
				border: 1px solid black;
			}
			button{
				padding: 2px 6px 2px 6px;
			}
			
			input{
				margin-top: 5px;
				margin-bottom: 10px;
			}
			.add_box{
				display: none;
			}
			.redact_box{
				display: none;
			}

CSS 样式主要用于设置页面的布局和元素的外观,包括表格的边框、内边距,按钮和输入框的样式,以及添加和编辑框组的初始隐藏状态。

JavaScript 

let body = document.getElementsByTagName('tbody')[0];
let data;
let total_price = document.getElementsByClassName('total_price')[0];
let total_num = document.getElementsByClassName('total_num')[0];
let maxId = 0;
let total;
let count;

let xhr = new XMLHttpRequest();
xhr.open('get', 'js/shop.json', true);
xhr.send();
xhr.onreadystatechange = function() {
	if (xhr.readyState == 4 && xhr.status == 200) {
		let text = xhr.responseText;
		console.log(text);
		data = JSON.parse(text);
		console.log(data);
		for (let i = 0; i < data.length; i++) {
			if (data[i].id > maxId) {
				maxId = data[i].id;
			}
		}
		reader();
	}
};

// 渲染函数
function reader() {
	count = 0;
	total = 0;
	console.log(data);
	let str = '';
	for (let i = 0; i < data.length; i++) {
		str += `
		<tr>
			<td>${data[i].name}</td>
			<td>${data[i].price}</td>
			<td>
				<button onclick='saveData(${i}, ${2})'>-</button>
				${data[i].num}
				<button onclick='saveData(${i}, ${1})'>+</button>
			</td>
			<td>
				<button onclick='display(${i})'>编辑</button>
				<button onclick='saveData(${i}, ${3})'>删除</button>
			</td>
		</tr>
		`;
		count += data[i].num * 1;
		total += data[i].price * data[i].num;
	}
	body.innerHTML = str;
	// 将价格和数量分别输出到页面,将价格保留至最多两位小数
	total_price.innerHTML = count.toFixed(2);
	total_num.innerHTML = total * 1;
}


/* 
 * 加减删除
 * @params  int index  下标
 * @params  int type   操作类型  1 加  2减  3删除
 */
function saveData(index, type) {
	if (type == 1) {
		data[index].num++;
	} else if (type == 2) {
		if (data[index].num > 0) {
			data[index].num--;
		}
	} else if (type == 3) {
		data.splice(index, 1);
	}
	reader();
}


// 添加函数
let names = document.getElementsByClassName('add_name')[0];
let prices = document.getElementsByClassName('add_price')[0];
let numbers = document.getElementsByClassName('add_num')[0];
// 编辑
let edit_name = document.getElementsByClassName('edit_name')[0];
let edut_price = document.getElementsByClassName('edut_price')[0];
let edit_num = document.getElementsByClassName('edit_num')[0];


// 显示
function display(index) {
	if (index == undefined) {
		names.value = '';
		prices.value = '';
		numbers.value = '';
		document.getElementsByClassName('add_box')[0].style.display = 'block';
	} else {
		// 点击编辑按钮后
		// 将对应行的名称、价格以及总数量渲染到输入框里
		edit_name.value = data[index].name;
		edut_price.value = data[index].price;
		console.log(edit_name);
		edit_num.value = data[index].num;
		// 存储一个值放id
		sessionStorage.setItem('ID', data[index].id);
		// 最后显示编辑的输入框
		document.getElementsByClassName('redact_box')[0].style.display = 'block';
	}
}

// 确定按钮函数
/* 
 * 
 */
function ensure(status) {
	if (status == 1) {
		let shopName = names.value;
		let shopPrice = prices.value;
		let shopNumber = numbers.value;
		// 判断价格是否小于0或者为空或名字为空,或数量小于0或为空或大于0不是整数
		if (Number(shopPrice) < 0) {
			alert('是负数');
		} else if (shopName == '') {
			alert('商品名不能为空');
		} else if (shopPrice == '') {
			alert('商品价格不能为空');
		} else if (shopNumber == '') {
			alert('商品数量不能为空');
		} else if (Number(shopNumber) < 0) {
			alert('商品数量不能小于零');
		} else if (shopNumber % 1 != 0) {
			alert('商品数量要为整数');
		} else {
			console.log('哈哈');
			// 当不满足以上条件时,
			maxId++;
			data.push({
				name: shopName,
				id: maxId,
				price: shopPrice,
				num: shopNumber
			});
			// 点击确定后隐藏输入框
			document.getElementsByClassName('add_box')[0].style.display = 'none';
		}
	} else if (status == 2) {
		// 点击确定后
		// 获取到输入框里各自的value值
		let shopNames = edit_name.value;
		let shopPrices = edut_price.value;
		let shopNumbers = edit_num.value;
		// 判断条件是否合格,像添加一样
		if (parseInt(shopPrices) < 0 || shopNames == '' || Number(shopNumbers) < 0 || shopNumbers > 0 &&
			shopNumbers % 1 != 0) {
			alert('不符合添加条件哦');
		} else {
			// 当符合条件后
			// for循环,循环data
			for (let i = 0; i < data.length; i++) {
				// 判断下标的id等不等于存储的id
				if (data[i].id == sessionStorage.getItem('ID')) {
					// 当相等时将1输入框里的值渲染到对应行
					data[i].name = shopNames;
					data[i].price = shopPrices;
					data[i].num = shopNumbers * 1;
					break;
					// 结束循环
				}
			}
			// 隐藏输入框
			document.getElementsByClassName('redact_box')[0].style.display = 'none';
		}
	}
	// 渲染到页面
	reader();
}


// 取消函数
function cancels(status) {
	if (status == 1) {
		document.getElementsByClassName('add_box')[0].style.display = 'none';
	} else if (status == 2) {
		document.getElementsByClassName('redact_box')[0].style.display = 'none';
	}
}
代码解释
  1. 数据:从 js/shop.json 文件中获取商品数据,并转化为 JavaScript 对象。同时,找出最大的商品 ID,以便后续添加新商品时生成唯一的 ID,而不会与之前的商品重复。
  2. 渲染函数 reader:遍历商品数据,生成表格行的 HTML 字符串,并将其插入到表格的 <tbody> 中。同时,计算商品的总价和总数量,渲染到页面上。每次数据更新后都要重新渲染。
  3. 操作函数 saveData:根据传入的 index 和 type 参数,对商品的数量进行加减操作或删除商品。操作完成后,调用 reader 函数重新渲染页面。
  4. 显示函数 display:根据是否传入 index 参数,决定显示添加商品的输入框还是编辑商品的输入框,并将对应商品的信息填充到输入框中。
  5. 确定按钮函数 ensure:根据 status 参数判断是添加商品还是编辑商品,对输入的信息进行验证,若验证通过,则更新商品数据,并重新渲染页面。
  6. 取消函数 cancels:根据 status 参数隐藏添加或编辑商品的输入框。

JSON 数据

[
	{
		"id":1,
		"name":"保温杯",
		"price": 89,
		"num":0
	},
	{
		"id":2,
		"name": "小推车置物架",
		"price":15.9,
		"num":0
	},
	{
		"id":3,
		"name": "活力28薰衣草",
		"price": 7.8,
		"num":0
	},
	{
		"id":4,
		"name": "娃哈哈AD钙奶",
		"price": 8.1,
		"num":0
	},
	{
		"id":5,
		"name": "垃圾桶",
		"price": 12.9,
		"num":0
	}
]

 JSON 数据包含了初始的商品信息,每个商品对象包含 idnameprice 和 num 四个属性。

通过以上代码流程,我们就制作好了一个简单的基础购物车功能,希望本文能对你理解和实现购物车功能有所帮助。有问题我们也可以在评论区进行讨论~

相关文章:

  • Python asyncio 入门实战-1
  • 高级:Redis 面试题精讲
  • 前端快速入门
  • 【C++】内存分配与释放、内存碎片、内存泄漏、栈溢出
  • 大模型应用开发SpringAI实战-开发自己的MCP服务
  • 深入解析xDeepFM:结合压缩交互网络与深度神经网络的推荐系统新突破
  • Vue2,Vue3知识大全
  • 费马引理和罗尔定理
  • 解密CHASE-SQL和XiYan-SQL多智能体AI如何最终实现TEXT2SQL的突破
  • 嵌入式通信篇---通信频段
  • CSS 背景属性学习笔记
  • ‌JVM 调优核心步骤与参数配置‌‌
  • Keil调试STM32:未定义OS_EVENT以及停在“BEAB BKPT 0xAB”处等问题
  • Java微服务注册中心深度解析:环境隔离、分级模型与Eureka/Nacos对比
  • Vue3性能优化终极指南:编译策略、运行时调优与全链路监控
  • Dubbo(53)如何在Spring Boot中集成Dubbo?
  • 批量给dwg显示略缩图_c#插件实现(com)
  • Tkinter图像和多媒体处理
  • 【深度学习】PyTorch实现VGG16模型及网络层数学原理
  • OpenCV 图像拼接
  • 让“五颜六色”面孔讲述上海故事,2025年上海城市推荐官开启选拔
  • 构建菌株有效降解有机污染物,上海交大科研成果登上《自然》
  • 纽约大学朗格尼医学中心的转型带来哪些启示?
  • 眉山“笑气”迷局:草莓熊瓶背后的隐秘与危机
  • 深入贯彻中央八项规定精神学习教育中央第七指导组指导督导中国船舶集团见面会召开
  • 国家主席习近平抵达莫斯科