一段时间不写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)'); }