学习来源: https://www.bilibili.com/video/BV1HJ41147DG
因为是模拟仿造,所以样式比较简便
全选
相关链接:https://blog.youkuaiyun.com/qq_45645902/article/details/106041119
增减商品数量
相关链接:https://blog.youkuaiyun.com/qq_45645902/article/details/106120971
修改商品小计
思路
1.每次点击+号或者-号,根据文本框的值 x 当前商品的价格 = 商品的小计
2.注意1:只能增加本商品的小计,就是当前商品的小计模块(p-sum)
3.修改普通元素的内容是text()方法
4.注意2:当前商品的价格,要把¥符号去掉再相乘,截取字符串 substr(1)
5.parents(‘选择器’) 可以返回指定祖先元素
<body>
<div class="one">
<div class="two">
<div class="three">
<div class="four">返回指定祖先元素</div>
</div>
</div>
</div>
<script>
console.log($(".four").parent().parent().parent());
console.log($(".four").parents());
console.log($(".four").parents(".two"));
</script>
</body>
6.最后计算的结果如果想要保留2位小数 通过 toFixed(2) 方法
7.用户也可以直接修改表单里面的值,同样要计算小计。 用表单change事件
8.用最新的表单内的值 x 单价 = 当前商品小计
代码:往下拉进度条看总代码
计算总计和总额
思路
1.把所有文本框里面的值相加就是总计数量。总额同理
2.文本框里面的值不相同,如果想要相加需要用到each
遍历。声明一个变量,相加即可
3.点击+ -,会改变总计和总额,如果用户修改了文本框里面的值同样会改变总计和总额
4.因此可以封装一个函数求总计和总额的,以上2个操作调用这个函数即可。
5.总计是文本框里面的值相加用val()
,总额是普通元素的内容用text()
6.要注意普通元素里面的内容要去掉¥并且转换为数字型才能相加
代码:往下拉进度条看总代码
删除商品模块
思路
1.把商品remove()
删除元素即可
2.有三个地方需要删除: 1. 商品后面的删除按钮 2. 删除选中的商品 3. 清理购物车:将购物车内所有商品删除
3.商品后面的删除按钮: 一定是删除当前的商品,所以从 $(this)
出发
4.删除选中的商品: 先判断小的复选框按钮是否选中状态,如果是选中,则删除对应的商品
5.清理购物车: 则是把所有的商品全部删掉
代码:往下拉进度条看总代码
选中的商品添加背景
思路
1.选中的商品添加背景,不选中移除背景
2.全选按钮点击:如果全选是选中的,则所有的商品添加背景,否则移除背景
3.小的复选框点击: 如果是选中状态,则当前商品添加背景,否则移除背景
4.背景可以通过类名修改,添加类和删除类
代码:往下拉进度条看总代码
总代码
为了文章方便预览和复制粘贴到编译器上,本代码在同一个文件内,实际写法中要记得分文件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>模拟购物车案例</title>
<script src="jquery.min.js"></script>
<style>
/* 公共样式 */
* {
/* 清除内边距、外边距 */
margin: 0;
padding: 0;
}
table {
border: 1px solid #e7e7e7;
border-right: none;
border-collapse: collapse;
}
th,
td {
text-align: center;
padding: 8px 20px;
border-bottom: 1px solid #e7e7e7;
border-right: 1px solid #e7e7e7;
}
th {
color: #fff;
background-color: deepskyblue;
}
input[type=checkbox] {
cursor: pointer;
}
a {
color: #666;
text-decoration: none;
}
a:hover {
color: #e33333;
}
em {
/* 斜体的文字不倾斜 */
font-style: normal;
}
button {
/* 当鼠标经过button时,鼠标变成小手形状 */
cursor: pointer;
background-color: transparent;
}
button {
font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif;
/* 去掉默认的灰色边框 */
border: 0;
/* 去掉默认的获得焦点后的蓝色边框 */
outline: none;
}
/* 商品详细模块 */
.decrement,
.increment {
float: left;
border: 1px solid #cacbcb;
height: 18px;
line-height: 18px;
padding: 1px 0;
width: 16px;
text-align: center;
color: #666;
margin: 0;
background: #fff;
margin-left: -1px;
}
.itxt {
float: left;
border: 1px solid #cacbcb;
width: 42px;
height: 18px;
line-height: 18px;
text-align: center;
padding: 1px;
margin:</