实现功能:
1、购物车全选与全不选
2、删除选中商品
3、直接删除商品
4、数量和价格修改
5、计算总价
$(function(){
//全选与全不选
$("#allCheckBox").click(function (){
var flag=$(this).is(":checked"); //记录此时全选框的状态
$("input[name='cartCheckBox']").each(function (){ //遍历所有cartCheckBox复选框
$(this).prop("checked",flag); //让复选框cartCheckBox的check与全选框保持一致
});
});
//删除选中商品
$("#deleteAll").click(function (){ //如果点击删除所选按钮,就会删除选中商品
$("input[name='cartCheckBox']:checked").each(function (){ //遍历选中的复选框
n=$(this).parents("tr").index();//获取复选框的行的顺序
$("table#shopping").find("tr:eq("+n+")").remove();
$("table#shopping").find("tr:eq("+(n-1)+")").remove();//移除该行与上一行(上一行为店铺名称)
});
productCount();
});
//直接删除商品
$(".cart_td_8").find("a").click(function (){
var link=$(this).parents("tr").index();
$("table#shopping").find("tr:eq("+link+")").remove();
$("table#shopping").find("tr:eq("+(link-1)+")").remove();
productCount();
});
//数量和价格修改
$('#shopping').find('.cart_td_6').find('img').filter('[alt="minus"]').click(function (){
var t=$(this).parent().find(".num_input");
if (t.val()==""||undefined||null){
t.val(0);
}
t.val(parseInt(t.val())-1);
if (parseInt(t.val())<0){
t.val(0);
}
productCount();
});
$('#shopping').find('.cart_td_6').find('img').filter('[alt="add"]').click(function() {
var t = $(this).parent().find(".num_input");
if(t.val()==""||undefined||null){
t.val(0);
}
t.val(parseInt(t.val()) + 1);
productCount();
});
//计算总价
function productCount(){
var $tr=$("#shopping").find("tr[id]");
var summer=0;
var integral=0;
$tr.each(function(i,dom){
var num=$(dom).children(".cart_td_6").find("input").val();//商品数量
var price=num*$(dom).children(".cart_td_5").text();//商品小计
$(dom).children(".cart_td_7").html(price);//显示商品小计
summer+=price;//总价
integral+=$(dom).children(".cart_td_4").text()*num;//积分
});
$("#total").text(summer);
$("#integral").text(integral);
}
});
运行结果: