实现简单的购物车

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Document</title>

    <style>

      table {

        border-collapse: collapse;

      }

      td {

        border: 1px solid gray;

        padding: 10px;

        text-align: center;

      }

    </style>

  </head>

  <body>

    <table>

      <thead>

        <tr>

          <td><input type="checkbox" />全选</td>

          <td>序号</td>

          <td>商品名</td>

          <td>单价</td>

          <td>数量</td>

          <td>小计</td>

        </tr>

      </thead>

      <tbody>

        <tr>

          <td>xxx</td>

          <td>xxx</td>

          <td>xxx</td>

          <td>

            <button>-</button>

            <span>xxx</span>

            <button>+</button>

          </td>

          <td>xxx</td>

        </tr>

      </tbody>

      <tfoot>

        <tr>

          <td colspan="6">合计:xxx</td>

        </tr>

      </tfoot>

    </table>

    <script>

      const products = [

        { name: '苹果', price: 10, count: 30, checked: true },

        { name: '香蕉', price: 6, count: 3, checked: true },

        { name: '柿子', price: 26, count: 1, checked: true },

        { name: '哈密瓜', price: 19, count: 45, checked: true },

      ]

      const products_el = products.map((value, index) => {

        const { count, name, price, checked } = value

        // 添加自定义属性: index, 保存序号

        return `<tr data-index='${index}'>

          <td><input type="checkbox" ${checked ? 'checked' : ''} /></td>

          <td>${index + 1}</td>

          <td>${name}</td>

          <td>¥${price}</td>

          <td>

            <button ${count == 1 ? 'disabled' : ''}>-</button>

            <span>${count}</span>

            <button>+</button>

          </td>

          <td>¥${price * count}</td>

        </tr>`

      })

      document.querySelector('tbody').innerHTML = products_el.join('')

      // 难点1: + 和 -

      // 思路1: 查询所有的按钮, 遍历挨个添加 事件

      // 思路2: 委托 -> 只需要给按钮共同的父元素添加事件

      const tbody = document.querySelector('tbody')

      tbody.onclick = function (e) {

        // 过滤出按钮的点击

        if (e.target.localName == 'button') {

          console.log(e.target)

          // 按钮的 父元素 的 父元素的  自定义属性.index

          const index = e.target.parentElement.parentElement.dataset.index

          console.log('序号:', index)

          // 现在场景: 页面是通过数据数组生成的, 他们应该联动

          if (e.target.innerHTML == '+') {

            products[index].count++

          }

          if (e.target.innerHTML == '-') {

            products[index].count--

          }

          console.log(products)

          //更新对应序号的界面

          updateCell(index)

        }

      }

      // 数据变化后, 要同步更新对应的栏目

      function updateCell(index) {

        // 通过序号, 从tbody孩子中, 找到对应的一条

        const cell = tbody.children[index]

        const subtotal = cell.lastElementChild //小计元素

        // 数量: 小计上方元素的孩子中的序号1

        const count_el = subtotal.previousElementSibling.children[1]

        // 从数据数组中, 读取 单价 和 数量

        const { count, price } = products[index]

        // 把数据 赋值给 元素内容

        count_el.innerHTML = count

        subtotal.innerHTML = '¥' + price * count

        // -按钮

        const jian_el = count_el.previousElementSibling

        // 数量==1 是true, 则说明 不可用是 true

        // jian_el.disabled = count == 1 ? true : false

        jian_el.disabled = count == 1

        // 更新合计

        updateTotal()

      }

      //合计

      function updateTotal() {

        // 数组高阶函数: reduce, 合并归纳数组数据

        // sum是总和, 0是初始值, value是每次遍历的元素

        const total = products.reduce((sum, value) => {

          const { price, count, checked } = value

          // 只累加 勾选的元素的价格, 此处利用 true1 false0

          // 乘以 checked, 如果是false, 不勾选,就是0, 不累加

          return sum + price * count * checked

        }, 0)

        // 获取合计元素

        const total_el = document.querySelector('tfoot td')

        total_el.innerHTML = '合计: ¥' + total

      }

      // 初始时: 触发一次总和

      updateTotal()

      // 全选按钮初始状态:  数组中的每一个都是勾选,则全选真的

      const cha = document.querySelector('thead input')

      // 忘记的人: 回顾 JSCORE 的day03

      cha.checked = products.every(value => value.checked)

      // 全选按钮变化时, 让其他勾选都变化

      cha.onchange = function () {

        //找到其他的所有按钮

        const chs = document.querySelectorAll('tbody input')

        // 遍历每一项, 让其勾选状态 和 全选按钮的一致

        chs.forEach(value => (value.checked = cha.checked))

        // 同步更新数据中的 checked

        products.forEach(value => (value.checked = cha.checked))

        // 重新算总和

        updateTotal()

      }

      // 为每一个单选按钮, 添加change事件:

      const chs = document.querySelectorAll('tbody input')

      chs.forEach(value => {

        value.onchange = function () {

          // 获取序号

          const index = this.parentElement.parentElement.dataset.index

          // 修改对应数据项的checked属性, 与当前选框的 选中状态一样

          products[index].checked = this.checked

          // 更新总价格

          updateTotal()

          // 全选按钮要跟随单选变化: 数据中的每一个元素, 都是勾选才是全选

          cha.checked = products.every(value => value.checked)

        }

      })

    </script>

  </body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的HTML代码实现简易购物车的示例: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>简易购物车</title> </head> <body> <h1>商品列表</h1> <ul> <li> <span>商品1</span> <span>100元</span> <button onclick="addToCart(1)">添加到购物车</button> </li> <li> <span>商品2</span> <span>200元</span> <button onclick="addToCart(2)">添加到购物车</button> </li> <li> <span>商品3</span> <span>300元</span> <button onclick="addToCart(3)">添加到购物车</button> </li> <li> <span>商品4</span> <span>400元</span> <button onclick="addToCart(4)">添加到购物车</button> </li> </ul> <h1>购物车</h1> <ul id="cart"> </ul> <p>总价:<span id="totalPrice">0</span>元</p> <script> // 初始化商品列表和购物车 const products = [ { id: 1, name: '商品1', price: 100 }, { id: 2, name: '商品2', price: 200 }, { id: 3, name: '商品3', price: 300 }, { id: 4, name: '商品4', price: 400 }, ] let cart = [] // 添加商品到购物车 function addToCart(id) { const product = products.find(p => p.id === id) if (product) { cart.push(product) // 更新购物车页面 const cartList = document.getElementById('cart') const item = document.createElement('li') item.innerHTML = `${product.name}(${product.price}元)<button onclick="removeFromCart(${product.id})">移除</button>` cartList.appendChild(item) // 更新总价 const totalPrice = document.getElementById('totalPrice') totalPrice.innerText = getTotalPrice() } else { alert('商品不存在') } } // 从购物车中移除商品 function removeFromCart(id) { const index = cart.findIndex(p => p.id === id) if (index !== -1) { cart.splice(index, 1) // 更新购物车页面 const cartList = document.getElementById('cart') cartList.removeChild(cartList.childNodes[index]) // 更新总价 const totalPrice = document.getElementById('totalPrice') totalPrice.innerText = getTotalPrice() } else { alert('购物车中不存在该商品') } } // 计算购物车总价 function getTotalPrice() { return cart.reduce((total, product) => total + product.price, 0) } </script> </body> </html> ``` 在这个示例中,我们首先定义了一个商品列表和一个购物车数组,然后在页面中显示了商品列表和购物车。每个商品都有一个“添加到购物车”按钮,点击后调用`addToCart`函数将该商品添加到购物车中。购物车中的每个商品都有一个“移除”按钮,点击后调用`removeFromCart`函数将该商品从购物车中移除。同时,页面上会显示购物车中的商品列表和总价,这些数据会在添加或移除商品时动态更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值