我在使用jquery时遇到问题。
我有一个ID为"#checkAll"的复选框和类为"checkbox"的复选盒。当ID为"checkAll"的复选框被选中时,我想打开所有复选框,当ID为"checkAll"的复选框被选中时,我想关闭所有复选框。
但是,现在的情况是,当我第一次单击复选框(#checkAll)时,所有其他复选框都会打开,当我首次打开复选框(#checkAll),所有其他的复选框也会关闭。
但是,当我第二次尝试单击复选框(#checkAll)时,所有其他复选框都没有打开
我不知道为什么会发生这种事。
请帮帮我!
这是我处理事件的javascript。
ADMIN.event = (function() {
function _init(){
$(function(){
var checkAll = $('#checkAll'),
checkboxes = $('.checkboxes');
checkAll.click(function(){
if($(this).is(':checked')){
checkboxes.attr('checked', 'checked');
} else {
checkboxes.removeAttr('checked');
}
})
});
}
_init();
}());
这是我在php中的视图文件。
<table class="fullTable">
<tr class="listTableTr">
<th class="listTableTh tinyTh"><input type="checkbox" name="" id="checkAll" /></th>
<th id="articleTitleTh" class="listTableTh">title</th>
</tr>
<?php foreach($postData as $post): ?>
<td class="listTableTd"><input type="checkbox" name="" class="checkboxes" /></td>
<td class="listTableTd"><a href="<?php echo 'index.php?r=admin/post/edit&post='.$post['id']; ?>"><?php echo $post['title'];?></a></td>
<?php endforeach; ?>
</table>
尝试使用类似的.prop()
checkAll.click(function(){
checkboxes.prop('checked',this.checked);
});
即使使用类似.on()
的也更好
checkAll.on('click' , function(){
checkboxes.prop('checked',this.checked);
});
试试这个:
$('#checkAll').on('click',function(){
if($("#checkAll").is(':checked')) {
$('.checkboxes').attr('checked',true);
} else {
$('.checkboxes').attr('checked',false);
}
});
演示
试试这个
$("#checkAll").click(function () {
if ($(this).is(":checked"))
$(".checkboxes").prop("checked","checked");
else
$(".checkboxes").prop("checked",false);
});