首先我們要實現的內容的需求有如下幾點:
1.在購物車頁面中,當選中“全選”復選框時,所有商品前的復選框被選中,否則所有商品的復選框取消選中。
2.當所有商品前的復選框選中時,“全選”復選框被選中,否則“全選”復選框取消選中。
3.單擊圖標-的時候數量減一而且不能讓物品小於0並且商品總價與積分隨之改變。
4.單擊圖標+的時候數量增加並且商品總價與積分隨之改變。
5.單擊刪除所選將刪除用戶選中商品,單擊刪除則刪除該商品即可並達到商品總價與積分隨之改變。
下面我們就開始進入代碼:
1 $(function () { 2 3 subtotal(); 4 addorminus(); 5 allcheckbox(); 6 delet(); 7 deleselect(); 8 }); 9 //設置 獲取積分和一共金額函數 10 function countmoney() { 11 var money = 0; //總金額 12 var jifen = 0; //總積分 13 $(".cart_td_7").each(function () { 14 var m = $(this).text(); 15 money += Number(m); 16 var j = $(this).siblings(".cart_td_4").text(); 17 var number = $(this).siblings(".cart_td_6").children("input").val(); 18 jifen += Number(j * number); 19 }); 20 $("#total").html(money); 21 $("#integral").html(jifen); 22 } 23 //小計 24 function subtotal() { 25 var obj = $(".cart_td_7"); 26 obj.each(function () { //each遍歷每一個clss為.card_td_7的元素 27 var num = $(this).siblings(".cart_td_6").children("input").val(); //購物車 選中的當前數量 28 var price = $(this).siblings(".cart_td_5").html(); //當前選中物品的price 29 var money = num * price; //小計 30 $(this).html(money); 31 }); 32 33 countmoney(); 34 35 } 36 //添加或減少數量 37 function addorminus() { 38 $(".hand").on("click", function () { 39 var num; 40 if ($(this).attr("alt") == "minus") { 41 num = $(this).next().val(); 42 if (num == 1) { 43 $(this).css("display", "none"); 44 } else { 45 $(this).next().val(--num); 46 } 47 } else { 48 num = $(this).prev().val(); 49 $(this).prev().val(++num); 50 if (num == 1) { 51 $(this).siblings("[alt==minus]").css("display", "visible"); 52 53 } else { } 54 } 55 subtotal(); 56 }); 57 } 58 59 //全選或者全不選 60 function allcheckbox() { 61 $("#allCheckBox").live("change", function () { 62 if ($(this).attr("checked") == "checked") { 63 $("[name=cartCheckBox]").attr("checked", "checked"); 64 } else { 65 $("[name=cartCheckBox]").attr("checked", false); 66 } 67 68 }); 69 70 $("[name=cartCheckBox]").live("change", function () { 71 var bool = true; 72 $("[name=cartCheckBox]").each(function () { 73 if ($(this).attr("cheked") != "checked") { 74 bool = false; 75 } 76 }); 77 if (bool) { 78 $("#allCheckBox").attr("checked", "checked"); 79 80 } else { 81 82 $("#allCheckBox").attr("checked", false); 83 } 84 }); 85 } 86 //刪除 87 function delet() { 88 $(".cart_td_8>a").live("click", function () { 89 $(this).parent().parent().prev().remove(); 90 $(this).parent().parent().remove(); 91 subtotal(); 92 }); 93 94 } 95 //刪除所選 96 function deleselect() { 97 $("#deleteAll>img").live("click", function () { 98 $("[name=cartCheckBox]").each(function () { 99 if ($(this).attr("checked") == "checked") { 100 $(this). parent().parent().prev().remove(); 101 $(this).parent().parent().remove(); 102 } 103 }); 104 subtotal(); 105 }); 106 }