進來開發中碰到一個比較奇怪的問題,就是用jquery控制界面中的checkbox全選和全不選的時候,
只能第一次成功使用不能重複操作。
代碼如下:
全選
$('input:checkbox').each(function(){
$(this).attr('checked',true);
});
全不選
$('input:checkbox').each(function(){
$(this).attr('checked',false);
});
在網上查說是jquery1.8以上存在這個問題,解決方法是用prop
全選
$('input:checkbox').each(function(){
$(this).prop('checked',true);
});
全不選
$('input:checkbox').each(function(){
$(this).prop('checked',false);
});
這種方式沒有在checkbox添加checked屬性。
於是用下面這種方式寫可以處理上面遇到的所有問題。
全選
$('input:checkbox').each(function(){
$(this).attr('checked',true);
$(this).prop('checked',true);
});
全不選
$('input:checkbox').each(function(){
$(this).attr('checked',false);
$(this).prop('checked',false);
});