购物车中的商品列表如下:

需求如下:
(1)实现如图所示商品列表
(2)单击’移出’按钮可用删除商品
(3)单击’全选’按钮选中所有商品
(4)根据用户的选择,统计购物车中的商品总价
- <div>
- <table border="1">
- <thead>
- <tr>
- <th>
- <input type="checkbox" id="all">全选
- th>
- <th>商品名称th>
- <th>单价(元)th>
- <th>数量th>
- <th>操作th>
- tr>
- thead>
- <tbody>
- tbody>
- table>
- <p>总价:<span id="totalPrice">span>p>
- div>
JavaScript代码
- let productList = [
- {
- id: 1,
- name: 'OPPOR17',
- price: 100,
- number: 3
- },
- {
- id: 2,
- name: '华为P10',
- price: 100,
- number: 2
- },
- {
- id: 3,
- name: 'iPhone7',
- price: 100,
- number: 1
- }
- ]
- // 获取数据
- function getProduct() {
- for (let i of productList) {
- $('tbody').append(`
-
-
-
${i.name} -
${i.price} -
${i.number} -
-
-
-
- `)
- }
- // 全选/取消全选
- $('#all').change(function () {
- $('.haha').attr('checked', this.checked)
- getPrice()
- })
- // 计算价格
- $('.haha').change(function () {
- // 如果所有复选框选中,则全选框也为选中
- if ($(".haha:checked").length == $(".haha").length) {
- $("#all").attr("checked", true);
- } else {
- $("#all").attr("checked", false);
- }
- getPrice();
- })
- }
- // 删除
- function del(item) {
- item.parent().parent().remove()
- }
-
- // 计算总价
- function getPrice() {
- let price = 0
- let count = 0
- let sum = 0
- // 获取价格
- $('.haha:checked').parents('.product').find('.price').each((index, element) => {
- price = parseInt($(element).text())
- })
- // 获取数量
- $('.haha:checked').parents('.product').find('.count').each((index, element) => {
- count = parseInt($(element).text())
- sum += price * count
- })
- // 将计算的金额显示
- $('#totalPrice').html(sum)
- }
-
