一段時間不寫js都有點忘記了,這里看幾個常見的js,涉及到循環,計算元素個數,checkbox選中等問題,首先是html元素
<div class="content border p05"><div><input type="checkbox" id="selectAll" name="selectAll">Select All</div><table><tbody><tr style="text-align: left;"><th> </th><th style="width:10%;">Qty</th><th>Descritpion</th><th>Item ID</th></tr><tr><td><input type="checkbox" class="item_id" value="29714200" name="item_id[]" style="width: 12px;"></td><td>25</td><td>Personalized Holiday CardsPersonalized Holiday Cards - 5" x 7" Cardstock - Standard Cardstock - White Envelopes</td><td>29714200</td></tr><tr><td style="text-align: center;padding-top:30px;" colspan="4"><div class="btn large step1">Submit</div></td><td></td></tr></tbody></table></div>
1.全選問題
$('#selectAll').click(function() {if($(this).attr('checked') == 'checked') {$("input[name='item_id[]']").attr("checked", true);//$('.item_id').attr('checked', true);var length = $('.item_id').length;$('#number').html(length); } else {$('.item_id').removeAttr('checked');$('#number').html(0);}});
注意判斷checkbox是否選中是"if($(this).attr('checked') == 'checked')",不是if($(this).attr('checked') == ture),但是很奇怪的是可以用true賦值$("input[name='item_id[]']").attr("checked", true);
?
2.判斷checkbox選中個數
$('.item_id:checked').length,這個寫法很簡潔的
?
3.循環元素,綁定函數
var num = 0;$.each($('.item_id'),function(i,v){if($(this).attr('checked') == 'checked'){num++;}});if(0 == num){alert('please select item(s)');return false;}
其實這寫法有點啰嗦,可以直接if(0==$('.item_id:checked').length){ alert('please select item(s)'); }
?