简单的js购物车结算
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>购物车</title><br> <script src="jquery-3.2.1.min.js"></script> <script src="CalcEval.js"></script> <style type="text/css"> .span_case{ display:inline-block; width:100px; } .item_goods{ display:inline-block; width:100px; } .item_price{ display:inline-block; width:100px; } .item_num{ color:green; } .item_total{ display:inline-block; width:100px; } .item_all{ color:red; } .total{text-align:right;width:345px;} </style> </head> <body> <div> <span class="span_case">商品名称</span> <span class="span_case">商品单价</span> <span class="span_case">商品数量</span> <span class="span_case">总价</span> </div> <div class="item"> <span class="item_goods">iphone 6s</span> <span class="item_price">1.10</span> <span class="span_case"> <input type="button" value="-"> <span class="item_num">5</span> <input type="button" value="+"> </span> <span class="item_total">5.00</span> <span class="delobj">删除</span> </div> <div class="item"> <span class="item_goods">iphone 7</span> <span class="item_price">2.03</span> <span class="span_case"> <input type="button" value="-"> <span class="item_num">2</span> <input type="button" value="+"> </span> <span class="item_total">4.00</span> <span class="delobj">删除</span> </div> <div class="item"> <span class="item_goods">iphone 8</span> <span class="item_price">3.00</span> <span class="span_case"> <input type="button" value="-"> <span class="item_num">2</span> <input type="button" value="+"> </span> <span class="item_total">6.00</span> <span class="delobj">删除</span> </div> <div class="item"> <span class="item_goods">iphone 9</span> <span class="item_price">1.00</span> <span class="span_case"> <input type="button" value="-"> <span class="item_num">2</span> <input type="button" value="+"> </span> <span class="item_total">2.00</span> <span class="delobj">删除</span> </div> <div class="total">合计金额:<span class="item_all">17.00</span></div> <script> $(function(){
//加 $("[value='+']").click(function(){ var z = $(this).prev("span").html(); z = parseInt(z)+1; $(this).prev("span").html(z); dgzj(this); jszj(); });
//减 $("[value='-']").click(function(){ var z = $(this).next("span").html(); z = parseInt(z)-1<0?0:parseInt(z)-1; $(this).next("span").html(z); dgzj(this); jszj(); }); //删除(清空) $(".delobj").click(function(){ //$(this).parent().remove(); var z = $(this).prev("span").html(); z=0; $(this).prev("span").prev("span").children("span").html(z); $(this).prev("span").html(z); jszj(); }); }) var ce = new CalcEval();//实例化计算的类 function dgzj(e){//单个商品的价格 var sl = $(e).parent().children("span").html(); var dj = $(e).parent().prev("span").html(); var zj = $(e).parent().next("span"); jg = ce.eval(parseInt(sl)+"*"+parseFloat(dj)); zj.html(jg); } function jszj(){//全部商品的价格 var num=0; $(".item_total").each(function() { num = ce.eval(num+"+"+parseFloat($(this).html())); }); $(".item_all").html(num); } </script> </body> </html>