思路
1.給tbody一個id=”shopList” 當進入購物車時如果有兩個商品被勾選了,需要計算出總價錢
2.當手動勾選商品時,也要把相應的價格加到總價中去
3.給全選添加一個id=”checkAll”當勾選全部選中時,要計算所有商品的總價要注意的是:這個函數,當單選是也要觸發,因爲當全部商品都勾選時也就相當調用了這個函數
4.當再次點擊全選時取消所有產品
5.當點擊+加號時也要計算
6.當點擊-加號時也要計算
7.文本框中也可以直接輸入,這裏需要校驗的地方比較多
8.當點擊刪除時,將選中的商品移除
代碼思路
1.首先計算總價
totalPrice();
function totalPrice(){
var lists = $('#shopList tr');
var total = 0;
lists.each(function(){
var _vm = $(this);
var isChecked = _vm.find('.checkbox').prop('checked');
if(isChecked){
var price = _vm.find('.price').text()*1;
var num = _vm.find('.num').val()*1;
total += price*num;
}
});
$('#total').text(total);
}
2.點擊勾選商品,改變總價
checkEvent();
function checkEvent(){
$('#shopList').on('click','.checkbox',function(){
totalPrice();
isCheckAll();
});
};
3.全部選中時的總價格
isCheckAll();
function isCheckAll(){
var len = $('#shopList .checkbox').length;
var clen = $('#shopList .checkbox:checked').length;
if(len === clen){
$('#checkAll').prop('checked',true);
}else{
$('#checkAll').prop('checked',false);
}
};
function isCheckAll(){
$('#checkAll').prop('checked',$('#shopList .checkbox').length === $('#shopList .checkbox:checked').length);
};
4.判斷全選是否是選中狀態
checkAllEvent();
function checkAllEvent(){
$('#checkAll').click(function(){
$('#shopList .checkbox').prop('checked',$(this).prop('checked'));
totalPrice();
});
};
5.單擊加號+計算價格
addEvent();
function addEvent(){
$('#shopList').on('click','.add',function(){
var _vm = $(this);
var num = _vm.prev().val()*1;
num++;
_vm.prev().val(num);
totalPrice();
isCheckAll();
});
}
6.單擊減號-計算價格
minusEvent();
function minusEvent(){
$('#shopList').on('click','.minus',function(){
var _vm = $(this);
var numNode = _vm.next();
var num = numNode.val()*1;
if(num >1){
num--;
}
numNode.val(num);
totalPrice();
isCheckAll();
});
};
7.文本框中直接改變數值
numEvent();
function numEvent(){
$('#shopList').on('keyup','.num',function(){
var _vm = $(this);
var num = _vm.val();
num = num.replace(/[^\d]+/g,'').replace(/^0+/,'');
_vm.val(num);
if(num){
totalPrice();
isCheckAll();
}
}).on('blur','.num',function(){
var _vm = $(this);
var num = _vm.val();
if(!num){
_vm.val(1);
}
totalPrice();
isCheckAll();
});
};
8.刪除
delEvent();
function delEvent(){
$('#shopList').on('click','.col_width_9 span',function(){
var isDel = confirm('您確定要刪除麼?');
if(isDel){
$(this).parents('tr').remove();
totalPrice();
}
});
}