首页 > 技术文章 > jQuery实现购物车多物品数量的加减+总价计算

yuancr 2018-04-09 07:48 原文

<script>

    $(function(){
        $(".add").click(function(){
            var t=$(this).parent().find('input[class*=text_box]');
            t.val(parseInt(t.val())+1)
            setTotal();
        })
        $(".min").click(function(){
            var t=$(this).parent().find('input[class*=text_box]');
            t.val(parseInt(t.val())-1)
            if(parseInt(t.val()) < 0){
                t.val(0);
            }
            setTotal();
        })
        function setTotal(){
            var s=0;
            $(".gm").each(function(){
                s+=parseInt($(this).find('input[class*=text_box]').val())*parseFloat($(this).find('span[class*=price]').text());
            });
            $("#total").html(s.toFixed(2));
        }
        setTotal();

    })
</script>

  html代码是随便先写出来的 没做调整 

 <div  class="gm">
                              <p style="font-family:'微软雅黑';font-size:16px;color:#333333;margin-top:25px;">Quantity</p>
                             <span class="price" style="display:none;">199</span>
                             <input class="add" name="" type="button" value="+" style="margin-top:-25px;float:right;width:30px;height:30px;border:1px solid #d8d8d8;background-color:#ffffff;" />

                             <input class="text_box" name="" type="text" value="1" style="margin-top:-25px;float:right;height:30px;width:30%;border:1px solid #d8d8d8;"/>
                             <input class="min" name="" type="button" value="-" style="margin-top:-25px;float:right;width:30px;height:30px;border:1px solid #d8d8d8;background-color:#ffffff;"/>
                             <img src="img/jinbicopy.png"style="width:25px;" alt=""><label id="total" style="color:#fba929;font-family:'微软雅黑';margin-top:20px;margin-left:5px;"></label>
                             <button type="button" style="margin-top:10px;color:#ffffff;font-size:17px;margin-bottom:15px;line-height:40px;width:95%;height:40px;text-align:center;margin-left:2.5%;border-radius:2px;border:1px solid #FBA929;background-color:#fba929">Submit</button>
                              <button type="button" style="color:#ffffff;font-size:17px;margin-bottom:15px;line-height:40px;width:95%;height:40px;text-align:center;margin-left:2.5%;border-radius:2px;border:1px solid #999999;background-color:#999999">Cancel</button>
                         </div>

  

 

推荐阅读