jQuery实现简单的纯前端的购物车案例

jQuery实现简单的纯前端的购物车案例

首先,我们需要知道目前主流的购物车功能都需要哪些功能。比如某宝的购物车功能,包括商品展示、勾选功能、结算功能等等。由于是练习这里还加入了增加数据的功能。

简单的页面展示:


由于只是简单的实现功能,这里就没有过于炫丽的页面展示,下面就需要实现功能了。

第一步,我们先实现如何才能将list里的数据绑定到tbody里

//添加行函数
function init(list) {
    var tb= $("table").children("tbody");
    var str;
    for(var i=0;i<=list.length;i++)
    {
        if(i>=list.length)
        {
         tb.append("");
        }
        else{
         str+=`<tr>
         <td><input type='checkbox' class="check" ></td>
         <td>${list[i].name}</td>
         <td>${list[i].brand}</td>
         <td>${list[i].country}</td>
         <td>${list[i].price}</td>
         <td><input type="button" class="sub"  value="-"><input class="input_num" type="text" value="0"><input type="button" class="add" value="+"></td>
         <td><span>0</span></td>
         <td><a href='#' class="del" >删除</a></td></tr>`;
        }  
    }
    tb.append(str);
 }

这里这个添加行函数实现了为tbody里动态添加tr,这里的参数是一个数据数组。需要注意的是,这里由于拼接字符串过于长会引起代码维护困难,这里使用的是ES6语法中的模板字符串拼接,详情请查阅ES6中的字符串(原作者:见嘉于世)

第二步,简单实现检索功能

这里需要说明的是,正常的购物车是没有检索功能的,但由于这个案例比较适合刚学完 jQuery 的新手练习,这里我们加入检索功能。

//检索查询函数
function chaxun(){
        var list1=list;
        var list2=[];
        $("table").children("tbody").children("tr").remove();
        var inputstr=$("#car_name").val();
        //list=所有的数据
        if(inputstr!="")  //判断输入框的值
        {
            for(var i=0;i<list.length;i++)
            {
                   if(list[i].name==inputstr)
                   {
                     list2.push(list[i]);
                   }
            }
            list1=list2;
            list2=[];
            $("table").children("tbody").children("tr").remove();
            init(list1);
        }
        if(optiontext!="请选择")  //判断下拉框的值
        {
          for(var i=0;i<list1.length;i++)
          {
              if(list1[i].country==optiontext)
              {
                list2.push(list1[i]);
              }
          }
          list1=list2;
          $("table").children("tbody").children("tr").remove();
          init(list1);
        }
        if(inputstr==""&&optiontext=="请选择")
        {
            $("table").children("tbody").children("tr").remove();
            init(list);
        }
}

这里的检索思想有很多,但只要是能够实现正确结果就可以了,但真正的大牛写的代码是非常简洁的,需要的是思维的成熟。

第三步,我们需要实现购物车的金额结算,总计功能和删除功能

这里需要注意的是,一开始就简单的实现金额结算和总计功能的时候,出现了执行完检索后,金额结算和总计功能失效的问题,经检查,是因为检索之后,将之前的tbody里的数据清除后又重新动态绑定数据后,之前的功能绑定失效,这里我们需要使用事件委派来解决该问题。详情请查看avaScript——事件委派之详解(作者: 一只野生饭卡丘),所以我们这里就使用事件委派写,也包括了删除功能。

//事件委托,解决检索后事件失效
$("table").on('click',function(event){
     if(event.target.className=="sub")
     {
           var price=event.target.parentElement.previousElementSibling.innerText;
           var num=event.target.nextElementSibling.value-1;
           if(num<=0)
           {
            event.target.parentElement.nextElementSibling.innerText=0;
            event.target.nextElementSibling.value=0;
            getSum();
           }
            else
            {
                event.target.nextElementSibling.value=num;
                num--;
                event.target.parentElement.nextElementSibling.innerText=(num+1)*price;
                getSum();
            }
    }
    if(event.target.className=="add")
    {
         var price=event.target.parentElement.previousElementSibling.innerText;
         var num=  parseInt( event.target.previousElementSibling.value) ;
         event.target.previousElementSibling.value= num+1 ;
         event.target.parentElement.nextElementSibling.innerText=(num+1)*price;
         getSum()
    }

    if(event.target.className=="check")
    {
         getSum()
    }
   if(event.target.className=="checkall")
   {
      if($("#cbxAll").prop("checked")==true){
          
        $(".check").prop("checked",true);
        getSum();
      }
      else{
        $(".check").prop("checked",false);
        getSum();
      }
   }
   if(event.target.className=="del")
   {
    event.target.parentElement.parentElement.remove();
    getSum();
   }
   quanxuan();
})
$("table").on("focusout",function(event){
    if(event.target.className=="input_num")
    {
        var price=event.target.parentElement.previousElementSibling.innerText;
        var num=event.target.value;
        event.target.parentElement.nextElementSibling.innerText=price*num;
        getSum();
    }
})

里面的getSum()和quanxuan()函数:

//合计函数
function getSum()
{
    var list=$(".check:checked");
    var allprice=0;
        for(var i=0;i<list.length;i++)
        {
           allprice+=parseInt(list[i].parentElement.parentElement.children[6].innerText);
        }
    $("#heji").text("合计:"+allprice);
}
//全选判断函数
function quanxuan(){
    if($(".check:checked").length== $(".check").length)
    {
        $("#cbxAll").prop("checked",true);
    }
    else{
        $("#cbxAll").prop("checked",false);
    }

}

第四步,实现添加功能

需要注意的是,正常的购物车页面也是没有添加功能的,这里也是为了练习对jQuery的熟练掌握。
这里我们的实现思路是点击添加按钮,跳页到一个新的窗口。这里我们需要知道window.open()方法。详情请见Window open() 方法,也就是父子页面进行数据的交换。

// An highlighted block
<script>
          $(function(){
            $("#btn").click(function(){
            var name=$("#name").val();
            var pinpai=$("#pinpai").val();
            var chandi=$("#chandi").val();
            var price=$("#price").val();
            var list1={name:name,brand:pinpai,country:chandi,price:price};
            window.opener.list.push(list1);
            // console.log( window.opener.list);
            window.opener.$("table").children("tbody").children("tr").remove();
            window.opener.init( window.opener.list);
            window.opener.$("select").children("option").remove();
            window.opener.addselect();
            window.close();
            });
        })
    </script>

全部代码:

主页面index.js代码:

$(function(){
    addselect();//动态给select添加option
    $("select").change(function(){
        optiontext=$(this).val();
 });
$("#heji").text("合计:0");//默认为0
//添加行
 init(list);
 //查询
 $("#chaxun").click(function(){
    chaxun();
 })

//事件委托,解决检索后事件失效
$("table").on('click',function(event){
     if(event.target.className=="sub")
     {
           var price=event.target.parentElement.previousElementSibling.innerText;
           var num=event.target.nextElementSibling.value-1;
           if(num<=0)
           {
            event.target.parentElement.nextElementSibling.innerText=0;
            event.target.nextElementSibling.value=0;
            getSum();
           }
            else
            {
                event.target.nextElementSibling.value=num;
                num--;
                event.target.parentElement.nextElementSibling.innerText=(num+1)*price;
                getSum();

            }
    }
    if(event.target.className=="add")
    {
         var price=event.target.parentElement.previousElementSibling.innerText;
         var num=  parseInt( event.target.previousElementSibling.value) ;
         event.target.previousElementSibling.value= num+1 ;
         event.target.parentElement.nextElementSibling.innerText=(num+1)*price;
         getSum()
    }

    if(event.target.className=="check")
    {
         getSum()
    }
   if(event.target.className=="checkall")
   {
      if($("#cbxAll").prop("checked")==true){
          
        $(".check").prop("checked",true);
        getSum();
      }
      else{
        $(".check").prop("checked",false);
        getSum();
      }
   }
   if(event.target.className=="del")
   {
    event.target.parentElement.parentElement.remove();
    getSum();
   }

   quanxuan();

})

$("table").on("focusout",function(event){
    if(event.target.className=="input_num")
    {
        var price=event.target.parentElement.previousElementSibling.innerText;
        var num=event.target.value;
        event.target.parentElement.nextElementSibling.innerText=price*num;
        getSum();
    }
})

$("#btnAdd").click(function(){
        window.open("add.html","name","height=300, width=300, top=200,left=700, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no")
    });

});

//合计函数
function getSum()
{
    var list=$(".check:checked");
    var allprice=0;
        for(var i=0;i<list.length;i++)
        {
           allprice+=parseInt(list[i].parentElement.parentElement.children[6].innerText);
        }
    $("#heji").text("合计:"+allprice);
}

//全选判断函数
function quanxuan(){
    if($(".check:checked").length== $(".check").length)
    {
        $("#cbxAll").prop("checked",true);
    }
    else{
        $("#cbxAll").prop("checked",false);
    }

}

 //查询函数
function chaxun(){
        var list1=list;
        var list2=[];
        $("table").children("tbody").children("tr").remove();
        var inputstr=$("#car_name").val();
         
        //list=所有的数据
    
        if(inputstr!="")
        {
            for(var i=0;i<list.length;i++)
            {
                   if(list[i].name==inputstr)
                   {
                     list2.push(list[i]);
                   }
            }
            list1=list2;
            list2=[];
            $("table").children("tbody").children("tr").remove();
            init(list1);
        }
        if(optiontext!="请选择")
        {
          for(var i=0;i<list1.length;i++)
          {
              if(list1[i].country==optiontext)
              {
                list2.push(list1[i]);
               
              }
          }
          list1=list2;
          $("table").children("tbody").children("tr").remove();
          init(list1);
        }
        if(inputstr==""&&optiontext=="请选择")
        {
            $("table").children("tbody").children("tr").remove();
            init(list);
        }
}
//添加行函数
function init(list) {
    var tb= $("table").children("tbody");
    var str;
    for(var i=0;i<=list.length;i++)
    {
        if(i>=list.length)
        {
         tb.append("");
        }
        else{
          str+=`<tr>
         <td><input type='checkbox' class="check" ></td>
         <td>${list[i].name}</td>
         <td>${list[i].brand}</td>
         <td>${list[i].country}</td>
         <td>${list[i].price}</td>
         <td><input type="button" class="sub"  value="-"><input class="input_num" type="text" value="0"><input type="button" class="add" value="+"></td>
         <td><span>0</span></td>
         <td><a href='#' class="del" >删除</a></td></tr>`;
        }  
    }
    tb.append(str);
 }

 //select添加option函数
 function addselect(){
     var arr=[];
     for(var i=0;i<list.length;i++)
     {
         arr.push(list[i].country);
     }
     var new_arr=[];
     for(var i=0;i<arr.length;i++) {
    var items=arr[i];
    //判断元素是否存在于new_arr中,如果不存在则插入到new_arr的最后
    if($.inArray(items,new_arr)==-1) {
      new_arr.push(items);
     }
     }
     $("select").append("<option>请选择</option>");
     for(var i=0;i<new_arr.length;i++)
     {
      $("select").append("<option>"+new_arr[i]+"</option>");
     }
 }
 var optiontext="请选择";
 var list = [{
     name: "奥托",
     brand: "铃木",
     country: "中国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "美国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "德国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "中国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "中国",
     price: "20000"
 }, 
 {
     name: "奥托",
     brand: "铃木",
     country: "中国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "美国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "德国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "中国",
     price: "20000"
 }, {
     name: "奥托",
     brand: "铃木",
     country: "法国",
     price: "20000"
 },];
 

主页面index.html代码:

<script src="index.js"></script>
    <style>
        table td  {
            width: 100px;
            border:1px solid #0094ff;
            text-align: center;
        }
        th{
            border:1px solid #0094ff;

        }
        .input_num{
            width: 20px;
            text-align: center;
        }
    #heji{
        font-size: 30px;
        color:red ;
        margin-left: 650px;
    }
    </style>
</head>
<body>
    <p>车型:<input type="text" name="" id="car_name">&nbsp;&nbsp; 国家:<select name="" id="selecttext">
    </select>&nbsp;&nbsp;
        <input type="button" id="chaxun" value="查询">&nbsp;&nbsp;<input type="button" id="btnAdd" value="添加">
    </p>

    <table>
        <thead>
            <th><input type="checkbox" name="" id="cbxAll" class="checkall"></th>
            <th>名称</th>
            <th>品牌</th>
            <th>产地</th>
            <th>价格</th>
            <th>数量</th>
            <th>合计</th>
            <th>操作</th>
        </thead>
        <tbody>
        </tbody>
    </table>
    <span id="heji"></span>
</body>

子页面代码:

<script>
          $(function(){
            $("#btn").click(function(){
            var name=$("#name").val();
            var pinpai=$("#pinpai").val();
            var chandi=$("#chandi").val();
            var price=$("#price").val();
            var list1={name:name,brand:pinpai,country:chandi,price:price};
            window.opener.list.push(list1);
            // console.log( window.opener.list);
            window.opener.$("table").children("tbody").children("tr").remove();
            window.opener.init( window.opener.list);
            window.opener.$("select").children("option").remove();
            window.opener.addselect();
            // window.close();


            });
        
        })
    </script>
</head>
<body>
    <p>名称:<input type="text"  id="name"/></p>
    <p>品牌:<input type="text"  id="pinpai"/></p>
    <p>产地:<input type="text"  id="chandi"/></p>
    <p>价格:<input type="text"  id="price"/></p>
    <p><input type="button" value="提交" id="btn" /></p>
</body>

乾坤未定,你我皆是黑马!!!
相信你将来也会成为一位大牛

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.ToString()°

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值