jq购物车案例

文章目录


前言

提示:在逛淘宝,京东网站中,我们会见到很多的购物车项目,接下来我就通过jq代码来实现一个简单的购物车案列。


提示:以下是本篇文章正文内容,下面案例可供参考

操作步骤

1.先画出简单的页面

 页面样式

<table>
        <thead>
            <tr>
                <th><input type="checkbox" id="ckAll"></th>
                <th>名称</th>
                <th>图片</th>
                <th>单价</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
        <tfoot>
            <tr>
                <td colspan="7" style="text-align: right;">
                    <span>总计:</span>
                    <span id="totalPrice"></span>
                </td>
            </tr>
        </tfoot>
    </table>

 2.设置css样式

<style>
        table {
            border-collapse: collapse;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 5px 10px;
            text-align: center;
        }

        img {
            width: 100px;
        }

        input {
            width: 30px;
            text-align: center;
        }
    </style>

  3.引入jq库

  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

 4.设置jq效果 

<script>
        // 商品数组
        let googs = [{
            name: "小米电视",
            img: "https://img10.360buyimg.com/n7/jfs/t1/191875/30/12237/92943/60e7a579E659a064c/f01cc6a90227c8f9.jpg",
            price: '3999',
            count: 2,
            isCk:true
        }, {
            name: "苹果手机",
            img: "https://img10.360buyimg.com/n7/jfs/t1/194022/20/10996/153505/60dc4c14Ea44f43f3/fa8c882d1fe46f4e.jpg",
            price: '6999',
            count: 4,
            isCk:false
        }, {
            name: "佳能相机",
            img: "https://img13.360buyimg.com/n7/jfs/t1/35828/26/5078/324781/5cbea100Eb22bb637/4d2d5e3bcd86fba4.jpg",
            price: '5999',
            count: 1,
            isCk:true
        }, {
            name: "西门子冰箱",
            img: "https://img13.360buyimg.com/n7/jfs/t1/188369/35/12392/145765/60e80460Eeebbc341/b50466dc4b98591d.jpg",
            price: '9999',
            count: 3,
            isCk:false
        }]

        // 循环数组,创建tr
        googs.forEach(g => {
            let tr = $('<tr>')
            let td0 = $('<td>').append($('<input type="checkbox" class="ck">').prop('checked',g.isCk))
            let td1 = $('<td>').html(g.name)
            let td2 = $('<td>').append($('<img>').attr('src', g.img))
            let td3 = $('<td>').html(g.price)
            let td4 = $('<td>').append($('<button class="jian">').html('-'))
                .append($('<input>').val(g.count))
                .append($('<button class="jia">').html('+'))
            let td5 = $('<td>').html(g.price * g.count)
            let td6 = $('<td>').append($('<button class="del">').html('删除'))

            tr.append(td0)
            tr.append(td1)
            tr.append(td2)
            tr.append(td3)
            tr.append(td4)
            tr.append(td5)
            tr.append(td6)
            $('tbody').append(tr)
        })

        // 给全选复选框注册点击事件
        $('#ckAll').click(function(){
            // attr()方法,用于获取 或 设置 元素的属性
            // prop()方法,也是用于获取 或 设置 元素的属性
            // 该方法,在读取bool值属性时返回的是true和false,在设置bool值属性时可以直接传true和false
            $('.ck').prop("checked",$('#ckAll').prop("checked"))

            //将复选框的状态更新回数据
            $('.ck').each(function(index,dom){
                googs[index].isCk = $(dom).prop("checked")
            })

            // 调用显示总价的方法
            totalPrice()
        })

        // 给其他复选框设置点击事件
        $('.ck').click(function(){
            $('#ckAll').prop('checked',[...$('.ck')].every(dom=>$(dom).prop('checked')))

            //将复选框的状态更新回数据
            $('.ck').each(function(index,dom){
                googs[index].isCk = $(dom).prop("checked")
            })

            // 调用显示总价的方法
            totalPrice()
        })

        // 删除按钮点击事件
        $('.del').click(function(){
            // 获取当前行的索引
            let index = $(this).parents("tr").index()
            // 删除当前行
            $(this).parents("tr").remove()
            // 删除当前行对应的数据
            googs.splice(index,1)
            
            // 调用显示总价的方法
            totalPrice()
        })

        // 减按钮点击事件
        $('.jian').click(function () {
            // 获取文本框里面的值
            let val = parseInt($(this).next('input').val())
            if (--val <= 0) val = 1
            // 更新文本框里面的值
            $(this).next('input').val(val)
            // 获取当前行的索引
            let index = $(this).parents('tr').index()
            // 更新对应商品的数量
            let g = googs[index]
            g.count = val
            // 更新显示小计
            $(this).parent().next('td').html(g.count * g.price)
            // 调用显示总价的方法
            totalPrice()
        })
        // 加按钮点击事件
        $('.jia').click(function () {
            // 获取文本框里面的值
            let val = parseInt($(this).prev('input').val())
            val++
            // 更新文本框里面的值
            $(this).prev('input').val(val)
            // 获取当前行的索引
            let index = $(this).parents('tr').index()
            // 更新对应商品的数量
            let g = googs[index]
            g.count = val
            // 更新显示小计
            $(this).parent().next('td').html(g.count * g.price)
            // 调用显示总价的方法
            totalPrice()
        })

        // 显示总价
        function totalPrice() {
            let totalPrice = googs.filter(r=>r.isCk===true).map(r => r.price * r.count).reduce(function (a, b) {
                return a + b
            }, 0)
            $('#totalPrice').html(totalPrice)
        }
        // 调用显示总价的方法
        totalPrice()
    </script>


总结

提示:购物车案列非常值得目前在学js和jq的小伙伴们,大家一起相互学习吧❥

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
假设你有一个商品列表,每个商品都有名称、价格和库存数量。你可以使用 jq 编写一个简单的购物车程序来处理用户的购买请求。以下是一个可能的实现: ```bash # 商品列表,格式为 JSON 数组 products='[ {"name": "apple", "price": 2.5, "quantity": 10}, {"name": "banana", "price": 1.5, "quantity": 5}, {"name": "orange", "price": 3, "quantity": 8}, {"name": "pear", "price": 2, "quantity": 12} ]' # 定义一个空的购物车,格式为 JSON 对象 cart='{"items": []}' # 处理用户输入,假设用户输入的是商品名称和购买数量,格式为 "name:quantity" input="apple:3" # 解析用户输入,获取商品名称和购买数量 name=$(echo "$input" | cut -d':' -f1) quantity=$(echo "$input" | cut -d':' -f2) # 查找商品列表中对应的商品 product=$(echo "$products" | jq ".[] | select(.name == \"$name\")") # 检查商品是否存在以及库存是否足够 if [ -z "$product" ]; then echo "Product not found" elif [ "$(echo "$product" | jq '.quantity')" -lt "$quantity" ]; then echo "Not enough stock" else # 将商品添加到购物车中 item=$(echo "$product" | jq ".quantity = $quantity") cart=$(echo "$cart" | jq ".items += [$item]") echo "Item added to cart" fi # 打印购物车内容 echo "$cart" | jq ``` 这个程序使用 jq 命令来解析和操作 JSON 数据。首先定义了商品列表和购物车的初始值,然后处理用户输入,并在商品列表中查找对应的商品。如果商品存在且库存足够,将商品添加到购物车中。最后打印购物车内容。你可以根据需要扩展这个程序,例如支持删除购物车中的商品、计算购物车总价等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值