jquery——购物车

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>购物车</title>
    
        <style>
            img{
                 150px;
                height: 100px;
            }
        </style>
        <script src="js/jquery-3.1.1.min.js"></script>
    
    </head>
    <body>
        
        <div align="center">
            <table id="tab" border="1" cellspacing="1px" cellpadding="6px">
                
                <!--标题-->
                <thead>
                <tr>
                    <th><input type="checkbox" id="chkAll" name="chkAll">全选</th>
                    <th>店铺宝贝</th>
                    <th>获积分</th>
                    <th>单价(元)</th>
                    <th>数量</th>
                    <th>小计(元)</th>
                    <th>操作</th>
                </tr>
                </thead>
                
                <!--    主体-->
                <tbody id="tbd">
                
                </tbody>
                
                <!--    脚注-->
                <tfoot align="right">
                <tr>
                    <td colspan="8">
                        <div>商品总价(不含运费):<span id="total">0</span>元</div>
                        <div>可获积分:<span id="totalPoints">0</span>点</div>
                    </td>
                </tr>
                <tr>
                    <td colspan="8">
                        <div align="left"><input type="button" value="删除所选" id="delAll"></div>
                    </td>
                </tr>
                </tfoot>
            </table>
            
            
            <div><input type="button" id="addAll" value="添加商品到购物车"></div>
        </div>
        <a href=""></a>
        <script>


            $(function () {

                //初始化内容
                //unitPrice代表单价,subtotal代表小计
                var data = [
                    {name: "<img src="https://bkimg.cdn.bcebos.com/pic/1b4c510fd9f9d72abc694104db2a2834349bbb9e?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg" alt="">
" +
                            "<br>Dell笔记本电脑", points: 5, unitPrice: 4000, number: 1, subtotal: 4000, operate:
                            "删除"},
                    {name:
                            "<img src="https://img.alicdn.com/imgextra/i2/1676045111/O1CN01gEcupR1ncss6N1BYk_!!0-item_pic.jpg_430x430q90.jpg" alt=""> <br>时尚芭莎杂志2020年1月/期迪士尼花木兰", points: 10, unitPrice: 30, number: 1, subtotal: 30, operate: "删除"},
                    {name:
                            "<img src="https://img.pconline.com.cn/images/product/6145/614547/1.jpg" alt=""><br>ipad pro", points: 10, unitPrice: 5000, number: 1, subtotal: 5000, operate: "删除"},

                ];


                $("#addAll").click(function () {

                    for (var i = 0; i < data.length; i++) {

                        var goods = data[i];

                        var $tr_goods =
                            $("<tr><td>" +
                                "<input type='checkbox'  name='chk' ></td><td >" +
                                goods.name
                                + "</td><td class='points'> " + goods.points
                                + "</td><td class=’unitPrice'>" + goods.unitPrice
                                + "</td><td>" + " <input type='button' class='minus' value='-'> "
                                + " <input type='text' value='1' name='number'  >  "
                                +
                                "&nbsp; <input type='button' value='+' class='add' > "
                                + "</td><td class='subtotal'>" + goods.subtotal + "</td><td>"
                                + "<input type='button' value='删除'  name='delOne' onclick='delOne(this)'>" +
                                "</td></tr>");

                        $tr_goods.appendTo($("#tbd"));

                    }

                });


                //增加数量
                $("#tbd").on('click', '.add', function () {

                    /*    //获取当前点击的所在行
                        var $tr = $(this).parent().parent();
    
                        //获取当前点击按钮所在行的数量文本框
                        var txtBox =$tr.find("td:eq(4)").find("input[name='number']");*/

                    //上边两行不可以简化为下边的,获取的是所有文本框的值了
                    //var txtBox =$("input[name='number']");
                    //下边这样也不对,$(this).prev() 已经是前一个标签啦
                    //var txtBox =$(this).prev().$("input[name='number']");

                    //获取当前点击按钮的前一个标签,即数量文本框
                    var txtBox = $(this).prev();


                    //获取当前点击按钮行的数量文本框的value值,即购买数量
                    //获取input标签的value值  val()获取值
                    var value = $(txtBox).val();

                    //获取单件商品积分
                    //放在商品数量改变前获取当前积分,容易计算
                    var point;
                    if(value==1){
                        point =$(this).parent().parent().find(".points").html();
                    }else {
                        point =$(this).parent().parent().find(".points").html();
                        point=point/(value);
                    }
                    
                    value = +value + 1;

                    //设置input标签的value值   val(str)设置值
                    $(txtBox).val(value);
                    
                    //获取点击按钮父节点td的前一列的标签的html内容,即单价
                    var unitPrice = $(this).parent().prev().html();
                    //    alert(unitPrice);
                
                    //设置点击按钮父节点td的前一列的标签的html内容,即小计
                    $(this).parent().next().html(value * unitPrice);
                    
                    var points =point*value;
                    $(this).parent().parent().find(".points").html(points);
                    
                    $("input[name=chk]").change();

                });

                //减少数量
                $("#tbd").on('click', '.minus', function () {
                    
                    var txtBox = $(this).parent().parent().find("td:eq(4)").find("input[name='number']");
                    var value = $(txtBox).val();

                    //获取单件商品积分
                    var point;
                    if(value==1){
                        point =$(this).parent().parent().find(".points").html();
                    }else {
                        point =$(this).parent().parent().find(".points").html();
                        point=point/(value);
                    }
                    
                    value = value - 1;
                    if (value <= 0) {
                        value = 1;
                        alert("商品数量必须大于0");
                    }
                    $(txtBox).val(value);
                    var unitPrice = $(this).parent().prev().html();
                    $(this).parent().next().html(value * unitPrice);
                    
                    var points =point*value;
                    $(this).parent().parent().find(".points").html(points);
                    
                    $("input[name=chk]").change();
                });

                //直接在文本框中添加数值(购买数量),小计和总计也要变化
                //    $("#tbd").on("change","input[name='number']",function ();识别的是填入文本框中的值变化,由加减号引起的文本框中的值变化无法识别
                $("#tbd").on("change", "input[name='number']", function () {
                    //最好把小计也提取成函数方法
                    var num = $(this).val();
                    var unitPrice1 = $(this).parent().parent().find("td:eq(3)").html();
                    $(this).parent().parent().children(".subtotal").html(unitPrice1 * num);
                    
                    var point =$(this).parent().parent().find("td:eq(2)").html();
                    $(this).parent().parent().find("td:eq(2)").html(point*num);
                    $("input[name=chk]").change();
                });

                //点击全选框,全选或全不选
                $("#chkAll").click(function () {

                    //prop()  用来获取或设置复选框的选中
                    var flag = $(this).prop("checked");

                    //遍历所有的子复选框
                    $("input[name=chk]").each(function () {
                        //如果全选框是选中的,子复选框也选中,否则,子复选框不选中
                        //也就是全选框的状态决定了子复选框的选中状态
                        this.checked = flag;
                    });

                    $("input[name=chk]").change();
                });


                //单选框全选,全选框也自动勾选
                //每个单选框点击的时候都要触发,所以把点击事件绑定到tbody下的所有子单选框上
                $("#tbd").on('click', 'input[name=chk]', function () {
                    //定义长度为所有子复选框的长度
                    //如果移除了一行,sum应该要变化
                    var sum = $("input[name=chk]").length;
                    var num = 0;

                    //遍历所有的子复选框
                    $("input[name=chk]").each(function () {
                        //如果当前子复选框的选中状态为true,num++
                        if ($(this).prop("checked")) {
                            num++;
                        }
                    });

                    //如果sum=0,即子复选框为0个,即所在商品行为0,此时,全选框不应该勾选
                    if (num === sum && sum !== 0) {
                        $("#chkAll").prop("checked", true)
                    } else {
                        $("#chkAll").prop("checked", false)
                    }

                    $("input[name=chk]").change();
                    
                });


                //点击删除所选
                $("#delAll").click(function () {
                    //遍历tbody下所有行
                    $("tbody tr ").each(function () {

                        //prop()  用来获取复选框的选中状态
                        //当前行下找到input标签中name属性为chk的标签,获取它(子复选框)的选中状态
                        var checked = $(this).find("input[name=chk]").prop("checked");

                        //如果选中,即选择移除
                        if (checked) {
                            //this代表当前行
                            //$(this)代表jQ中的this,与js中的this有区别
                            $(this).remove();
                        }
                    });

                    //判断如果商品行数为0,全选框不勾选
                    if($("tbody tr").length ===0){
                        $("#chkAll").prop("checked",false)
                    }
                    $("input[name=chk]").change();

                    //如果全部删除,触发不到子复选框
                    //需要单独使总价和总积分清零
                    if($("tbody tr").length === 0){
                        $("#total").html(0) ;
                        $("#totalPoints").html(0) ;
                    }
                });

                /*//删除单个商品
                //提问:为什么报错说del未声明,声明到外部就不报错
                //因为页面已经将JS加载完毕,此时新增请求动态添加节点,自然获取不到。
            //在网上查阅资料后发现动态添加的标签要事件委托才能获取到节点,也就是说要用:$(selector).on(events,[selector],[data],fn)
            // 解决办法:异步导致绑定事件失败。需使用全局绑定事件
                $('input[name=del]').click(function () {
                    $(this).parent().parent().remove();
                })*/

                //删除单个商品
                $("tbody").on('click', 'input[name=delOne]', function f() {
                    $(this).parent().parent().remove();

                    //判断如果商品行数为0,全选框不勾选
                    if($("tbody tr").length ===0){
                        $("#chkAll").prop("checked",false)
                    }
                    
                    $("input[name=chk]").change();
                    
                });

                //点击加按钮,这里的测试会弹出三次
                //当对象是'input[name=chk] , input[name =number]'时,点击加按钮,调用input[name=chk]变化,使测试被执行三次
                //当对象是'input[name =number]'时,点击加按钮,调用    $("input[name=chk]").change();测试不会执行
                //当对象是'input[name =number]'时,点击加按钮,调用$("input[name=number]").change();,测试也不会执行
                //结论$("input[name=number]").change();无效,或者说    $("table").on('change', 'input[name =number]', function()无效
                //提问:为什么$("table").on('change', 'input[name =number]', function()无效,而    $("table").on('change', 'input[name =chk]', function()可以识别执行
                //已解决:原因是$("table").on('change', 'input[name =number]', function(),只能是文本框输入内容改变才触发,点击按钮导致的文本框内容变化不会触发
                /*    $("table").on('change', 'input[name =number]', function() {
                        alert("测试")
                    });*/

                $("table").on('change', 'input[name =chk]', function () {
                    var totalMoney = 0;
                    var totalPoints = 0;
                    //    var $checkBox = $("#tbd input [name=chk]");
                    //var price = ($(this).parent().parent()).children(".subtotal").html();

                    $("input[name=chk]").each(function () {

                        //如果当前子复选框的属性是checked选中状态
                        if ($(this).prop("checked")) {

                            var price1 = ($(this).parent().parent()).children(".subtotal").html();

                            var price = parseFloat(price1);
                            totalMoney += price;
                            
                            var point1 =($(this).parent().parent()).children(".points").html();
                            var point =parseFloat(point1);
                            totalPoints +=point;
                        }
                    });

                    
                    $("#total").html(totalMoney);
                    $("#totalPoints").html(totalPoints);
                })
            });


            /*//删除单个
            function delOne(ele) {
                $(ele).parent().parent().remove();
                $("input[name=chk]").change();
            }*/


            /*    //根据商品数量和单价计算每行商品的小计
                //获取不到input[name=chk]
                            function totalMoney() {
                
                                var total = 0;
                
                                var $checkBox = $("#tbd input [name=chk]");
                
                                $("#tbd input[name=chk]").each(function () {
                                    //    var trs =$(this).parent().parent();
                
                
                                    //如果当前子复选框的属性是checked选中状态
                                    if ($(this).prop("checked")) {
                                    
                                        //通过获取当前行的价格文本,转换成小数然后叠加
                                        var price1 = $(this).parent().parent().eq(5).html();
                
                                        //var price = parseFloat(price1);
                                        total += price;
                                    }
                                });
                
                                $("#total").html(total);
                
                            }
                */

            //var price = parseFloat($("#tbd tr:eq(i) td:eq(5)").html());
            //    $("#tbd  td:eq(5)")
        </script>
    
    
    </body>
</html>
原文地址:https://www.cnblogs.com/longmo666/p/13264791.html