我需要有关自动检查 TreeView 中的复选框的帮助。
我有一个 TreeView ,当我单击复选框时,列表中的所有子项都会自动选中其复选框。问题是它不起作用。
treeview.find('input[type=checkbox]').each(function () {
$j(this).click(function () {
if ($j(this).is(':checked')) {
$j(this).siblings('ul').find('input[type=checkbox]').attr('checked', 'checked');
} else {
$j(this).siblings('ul').find('input[type=checkbox]').removeAttr('checked');
}
});
});
所以代码说明了一切,我找到了所有复选框,并且在每个复选框上绑定(bind)了单击事件。单击该项目时,它会检查是否已选中,然后查找所有复选框并将其属性设置为已选中,否则查找所有复选框并删除其已选中属性。我的选择器工作正常,所以这不是问题。
当我单击复选框时,所有复选框都会被选中,当我取消选中时,它仍然有效。但再试一次,就不行了!这很奇怪!最奇怪的是,当我检查代码时,我可以在复选框上看到它有 checked="checked"
但浏览器不会呈现选中状态(实际上这是主要问题)。
最佳答案
用途:
$el.prop('checked', true) // to check the box
$el.prop('checked', false) // to uncheck the box
而不是:
$el.attr('checked', 'checked') // to check the box
$el.removeAttr('checked') // to uncheck the box
这是因为您需要更改框的选中状态,而不是选中属性。 checked 属性仅用于复选框的初始状态。
关于jQuery 不会检查复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17279754/