定義全局變量
var sum =0;
var itemNumber = $(".goods-item").length;
//alert(itemNumber);
//建立數組存放單價
var prices = new Array(itemNumber);
for(var i=0;i<itemNumber;i++)
{
prices[i]=$('.goods-price').eq(i).html();
}
點擊複選框計算總價:效果如圖
$('.icon-xuanze1').on('click',function(){
$(this).toggleClass('color');
//alert(allPrice.length)
for(var i=0;i<itemNumber; i++){
//alert(itemNumber)
$('.icon-xuanze1').eq(i).attr("index",i);
}
//alert(allPrice.length)
if($('.icon-xuanze1').eq($(this).attr('index')).hasClass('color')){
sum += parseInt($('.goods-price').eq($(this).attr('index')).html());
}else{
sum -= parseInt($('.goods-price').eq($(this).attr('index')).html());
}
//alert(allPrice);
// var sum = 0;
// for(var i=0; i<allPrice.length;i++){
// sum += parseInt(allPrice[i]);
// }
// //alert(sum);
$('.all-price').html(sum)
})
點擊設置動態生成(點擊全選框)(刪除)(完成)
點擊(刪除)時。被選中的複選框remove。
總價歸零。
$('.icon-shezhi').on('click',function(){
$("<span class='allchooseBox'>").prependTo($(".goods-list"));
$('.allchooseBox').html('<i class="iconfont icon-xuanze"/>點擊全選');
$("<span class='finish'>").insertAfter($(".allchooseBox"));
$('.finish').html('完成');
$("<span class='delete'>").insertAfter($(".finish"));
$('.delete').html('刪除');
$('.icon-shezhi').css('display','none');
//點擊刪除,找到選中的,然後刪除
$('.delete').click(function(){
var num=0;
for(var i=0;i<$('.icon-xuanze1').length;i++){
if($('.icon-xuanze1').eq(i).hasClass('color')){
num++;
prices.splice(i, 1);//把price數組裏面刪除的goods-item的價錢刪除
//alert(prices);
$('.icon-xuanze1').eq(i).parent().remove();
i--;
itemNumber--;
}
// for(var j=0;j<itemNumber;j++){
// change(j);
// }
}
if(num==0){
alert('至少選一項')
}
if($('.icon-xuanze1').length == 0){
$('.allchooseBox').remove();
$('.delete').remove();
$('.remind').remove();
$('.finish').remove();
$('.foot-top').remove();
alert('你的購物車裏什麼都沒有。還不去逛逛');
}
$('.all-price').html(0);
})
//點擊全選,子元素全部選中,再點就全取消
$('.allchooseBox').on('click',function(){
$('.allchooseBox i').toggleClass('color');
if($('.allchooseBox i').hasClass('color')){
for(var i=0;i<$('.icon-xuanze1').length; i++){
$('.icon-xuanze1').eq(i).addClass('color');
}
}else{
for(var i=0;i<$('.icon-xuanze1').length;i++){
$('.icon-xuanze1').eq(i).removeClass('color');
}
}
})
//點擊完成,設置選項隱藏
$('.finish').click(function(){
$('.allchooseBox').remove();
$('.delete').remove();
$('.finish').remove();
$('.icon-shezhi').css('display','block');
sum = 0;
$('.all-price').html(sum);
for(var i=0; i<$('.icon-xuanze1').length; i++){
$('.icon-xuanze1').eq(i).removeClass('color');
}
})
})