jQuery实现购物车多物品数量的加减小计+总价计算

By柏小白

jQuery实现购物车多物品数量的加减小计+总价计算

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>jQuery实现购物车多物品数量的加减小计+总价计算</title>
    <script src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script>
$.each($('input[class*=text_box]'),function(i,t){
    subtotal($(t));
})
$(function(){
$(".add").click(function(){
    var t=$(this).parent().find('input[class*=text_box]');
    t.val(parseInt(t.val())+1);
    if(isNaN(t.val())){
        t.val(1);
    }
    subtotal(t)
});
$(".min").click(function(){ 
    var t=$(this).parent().find('input[class*=text_box]'); 
    t.val(parseInt(t.val())-1);
    if(parseInt(t.val())<=0 || isNaN(t.val())){ 
        t.val(1);
    }
    subtotal(t);
});
$('input[class*=text_box]').keyup(function(){
    var t=$(this);
    t.val(parseInt(t.val()));
    if (isNaN(t.val()) || parseInt(t.val()) <= 0) {
        t.val(1);
    }
    if (t.val(parseInt(t.val())) != t.val()) {
        t.val(parseInt(t.val()));
    }
    subtotal(t);
});
function subtotal(sum){
    var subtotal=0;
    subtotal=parseFloat(sum.siblings('.price').text())*parseInt(sum.val());
    sum.siblings('.subtotal').html(subtotal.toFixed(2));
    setTotal();
}
function setTotal(){
    var s=0; 
    $("#tab td").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></head>
<body>
    <table id="tab">
        <tr>
            <td>
                <span>单价:</span>
                <span class="price">1.50</span>
                <input class="min" name="" type="button" value="-" />
                <input class="text_box" name="" type="text" value="1" />
                <input class="add" name="" type="button" value="+" />
                <span class="subtotal">1.50</span>
            </td>
        </tr>
        <tr>
            <td>
                <span>单价:</span>
                <span class="price">3.95</span>
                <input class="min" name="" type="button" value="-" />
                <input class="text_box" name="" type="text" value="1" />
                <input class="add" name="" type="button" value="+" />
                <span class="subtotal">3.95</span>
            </td>
        </tr>
    </table>

    <p>
        总价:
        <label id="total"></label>
    </p>
</body>
</html>

 





jQuery实现购物车多物品数量的加减小计+总价计算


单价:
1.50



1.50
单价:
3.95



3.95

总价:


About the author

柏小白 administrator