购物车功能(JS,jQuery,HTML,css)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>购物车</title>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
  <style>
    table,th,td{
      border: 1px solid black;
    }
    table{
      border-collapse: collapse;
      margin-top: 30px;
      margin-bottom: 30px;
      width: 600px;
      text-align: center;
    }
    td,th{
      width: 120px;
    }
    button{
      border: 0;
    }
  </style>
</head>
<body>
<table>
  <tr>
    <th><button class="all">全选</button></th>
    <th>商品名称</th>
    <th>单价</th>
    <th>数量</th>
    <th>小计</th>
    <th>操作</th>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name="" class="getGoods">
    </td>
    <td>电脑</td>
    <td class="price">200</td>
    <td>
      <button class="jian">-</button>
      <span>1</span>
      <button class="add">+</button></td>
    <td class="total">200</td>
    <td>删除</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="" class="getGoods"></td>
    <td>手机</td>
    <td class="price">100</td>
    <td>
      <button class="jian">-</button>
      <span>1</span>
      <button class="add">+</button>
    </td>
    <td class="total">100</td>
    <td>删除</td>
  </tr>
</table>
<div>
  <span>总计:</span>
  <span class="sum"> 0</span>
</div>
<script>
  let flag = false;
  $('.add').click(function () {
    let num = parseInt($(this).prev().text());
    num++;
    $(this).prev().text(num)
    let price = parseInt($(this).parent().prev().text());
    $(this).parent().next().text(price * num);
    getSum()
  })
  $('.jian').click(function () {
    let sub = parseInt($(this).next().text());
    sub--;
    if(sub<1){
      return
    }
    $(this).next().text(sub)
    let price = parseInt($(this).parent().prev().text());
    $(this).parent().next().text(price * sub);
    getSum()
  })
  function getSum() {
    let sum = 0;

      for(let i = 0; i<$('.total').length; i++){
        if($('.total').eq(i).parent().find('input').prop('checked')){
          sum += parseInt($('.total').eq(i).text())
        }
      }

  $('.sum').text(sum)
  }
  $('.all').click(function () {
    $('.getGoods').prop('checked',true)
    getSum()
  })
  $('.getGoods').click(function () {
    getSum()
  })
  getSum()
</script>
</body>
</html>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值