javascript代码部分主要实现三部分功能
1、商品数量增加(减少)同时小计增加(减少)
这部分主要是通过for循环给增加(减少)按钮绑定点击事件
1)点击后计数器自增(自减)
2)计数器数量*对应商品单价 赋值给对应商品小计(涉及到数据类型转换)
parseInt('12ccc') → 12 (该方法常用于截断数值后面的单位)
2、封装一个用于计算总价和总量的函数
1)利用循环函数获取页面所有商品的小计和与数量和
2)将封装函数写进增加(减少)按钮绑定事件里面,使得每次点击都会重新计算小计与数量
注意:该函数要写在for循环外面
3、删除功能
1)给每个删除事件都要绑定一个点击事件,因此可以与增加减少按钮写在一个循环体内
2)这里主要用到了 父元素.removeChild(子元素)这个方法,这里要分清楚谁是父元素,谁是子元素,一定要找最近的父元素,不要混淆,而且要先获取父元素。
3)封装函数也要写在点击事件里面。
这里有个很容易出错的问题:就是删除该列商品后页面中的总价和总商品数量也需要发生对应的改变,因此封装函数需要重新去获取当前页面中的对应商品的数量以及小计,所以我们将获取元素的代码,写在封装函数里面,用于重新获取页面信息。参考局部变量与全局变量的作用域不同,因此不会互相影响。

购物车效果图如下所示:

css代码部分
* {
margin: 0;
padding: 0;
}
table {
border-spacing: 0;
border: 1px dashed #ccc;
width: 600px;
border-left: 0;
border-right: 0;
text-align: center;
/* 让表格居中 */
margin: 0 auto;
}
td {
border-spacing: 0;
border: 1px dashed #ccc;
border-top: 0;
border-left: 0;
border-right: 0;
width: 100px;
height: 100px;
}
th {
border-spacing: 0;
border: 1px dashed #ccc;
border-left: 0;
border-right: 0;
}
ul {
display: flex;
justify-content: center;
}
li {
display: flex;
float: left;
list-style: none;
justify-content: center;
}
.input {
height: 15px;
width: 35px;
text-align: center;
background-color: whitesmoke;
border: 1px solid darkred;
padding: 0;
margin: 0;
line-height: 15px;
}
.add {
height: 17px;
width: 10px;
text-align: center;
background-color: darkred;
text-align: center;
color: white;
line-height: 15px;
padding: 0;
margin: 0;
border:1px solid darkred;
}
.reduce {
height: 17px;
width: 10px;
text-align: center;
background-color: darkred;
text-align: center;
color: white;
line-height: 15px;
padding: 0;
margin: 0;
border:1px solid darkred;
}
.foot {
border: 1px solid #ccc;
border-top: 0;
width: 600px;
height:50px;
margin: 0 auto;
}
.jiesuan {
height:50px;
background-color: darkred;
width: 70px;
color:white;
border: 0;
font-size: 15px;
}
.bottom {
font-size: 15px;
float:right;
}
.jiesuan:hover {
background-color: plum
}
#totalNum {
color: darkred;
}
#total_price {
color: darkred;
}
.item:hover {
background-color: whitesmoke;
}
.item {
height: 100px;
}
购物车案例
| 全选 | 商品 | 单价 | 商品数量 | 小计 | 操作 |
|---|---|---|---|---|---|
![]() |
20¥ |
|
1 | ||
|
30¥ |
|
1 | ||
|
40¥ |
|
1 | ||
|
50¥ |
|
1 |
上一篇:DevOps(4)