標籤:分享 html span foo bsp val js代碼 代碼 check
本demo適合剛學習jQuery的戰友學習。
一個星期平均有4次晚上是吃 某荔村腸粉,所以內容就是我晚上經常點吃的那些。一般我都是吃14塊錢。
效果
HTML代碼:
1 <ul id=‘food‘> 2 <li><input type="checkbox" value=‘8‘>8元 紅豆沙</li> 3 <li><input type="checkbox" value=‘5‘>5元 青菜腸</li> 4 <li><input type="checkbox" value=‘2‘>2元 加底</li> 5 <li><input type="checkbox" value=‘7‘>7元 雞蛋青菜粥</li> 6 <li><input type="checkbox" value=‘6‘>6元 白灼鮮蔬菜</li> 7 <li><input type="checkbox" value=‘7‘>7元 黃金南瓜粥</li> 8 <li><input type="checkbox" value=‘3‘>3元 滷蛋</li> 9 </ul>10 <div>11 <input type="checkbox" id=‘all‘>12 <input type="button" value=‘全選‘ id=‘selectAll‘>13 <input type="button" value=‘全不選‘ id=‘unselectAll‘>14 <input type="button" value=‘反選‘ id=‘reverse‘>15 <input type="button" value=‘獲得選中的值‘ id=‘getnum‘>16 </div>
JS代碼:
1 <script src=‘./js/jquery.min.js‘></script> 2 <script> 3 //計算次數,當 #food 7個都選中時,#all 也選中 4 var num =0; 5 //#all 全選框選中時,#food 全部選中 6 $(‘#all‘).click(function(){ 7 if((this.checked)){ 8 $(‘#food :checkbox‘).prop(‘checked‘,true); 9 }else{10 $(‘#food :checkbox‘).prop(‘checked‘,false);11 }12 })13 //全選按鈕14 $(‘#selectAll‘).click(function(){15 $(‘:checkbox‘).prop(‘checked‘,true);16 num = 7;17 })18 //全不選按鈕19 $(‘#unselectAll‘).click(function(){20 $(‘:checkbox‘).prop(‘checked‘,false);21 num = 0;22 })23 //反選按鈕24 $(‘#reverse‘).click(function(){25 var arr = [];26 $(‘#food :checkbox‘).each(function(){27 $(this).prop(‘checked‘,!$(this).prop(‘checked‘));28 })29 $(‘#food>li>input‘).each(function(){30 if(this.checked){31 arr.push($(this).val());32 }33 });34 num = arr.length;35 if(num == 7){36 $(‘#all‘).prop(‘checked‘,true);37 }else{38 $(‘#all‘).prop(‘checked‘,false);39 }40 })41 //擷取價錢,顯示出來42 $(‘#getnum‘).click(function(){43 getNum();44 });45 //全部#food框都選中時,#all 也選中46 $(‘#food :checkbox‘).click(function(){47 if(this.checked){48 num++;49 }else{50 num--;51 }52 if(num == 7){53 $(‘#all‘).prop(‘checked‘,true);54 }else{55 $(‘#all‘).prop(‘checked‘,false);56 }57 })58 //計算價錢59 function getNum(){60 var sum = 0;61 var arr = [];62 $(‘#food>li>input‘).each(function(){63 if(this.checked){64 //取value值,為字串,轉為數字65 arr.push(Number($(this).val()));66 }67 });68 //遍曆數組,取合69 arr.forEach(function(i){70 sum += i;71 })72 alert("總共:"+ sum + "元");73 }74 75 </script>
簡單的jquery全選反選案例