你能做一个更好的代码吗?我需要根据父母检查/取消选中所有孩子,当孩子被检查时,检查父母,当所有孩子都未选中时取消选中父母。
$(".parent").children("input").click(function() {
$(this).parent().siblings("input").attr("checked", this.checked);
});
$(".parent").siblings("input").click(function() {
if (this.checked) {
$(this).siblings("div").children("input").attr("checked", true);
return;
}
var childs = $(this).siblings("div").siblings("input");
for (i = 0; i < childs.length; i++) {
if ($(childs.get(i)).attr("checked"))
return;
}
$(this).parent().children("div").children("input").attr("checked", false);
});
答案 0 :(得分:1)
$(".parent").children("input").click(function() {
$(this).parent().siblings("input").attr("checked", this.checked);
});
$(".parent").siblings("input").click(function() {
$(this).siblings("div").children("input").attr("checked",
this.checked || $(this).siblings("input[checked]").length>0
);
});
答案 1 :(得分:1)
<div class="parent">
<input type="checkbox" />
<div>
<input type="checkbox" />
<input type="checkbox" />
</div>
<input type="checkbox" />
<div>
<input type="checkbox" />
<input type="checkbox" />
</div>
</div>
这是我使用的代码。
$("input[type='checkbox']").click(function() {
// turn on or off all descendants.
$(this) // get this checkbox
// get the div directly after it
.next('div')
// get ALL the inputs in that div (not just first level children)
.find("input[type='checkbox']")
.attr("checked", this.checked)
;
// now check if we have to turn the parent on or off.
$(this)
.parent() // this will be the div
.prev('input[type="checkbox"]') // this is the input
.attr(
"checked", // set checked to true if...
this.checked // this one is checked, or...
|| $(this).siblings("input[type='checkbox'][checked]").length > 0
// any of the siblings are checked.
)
;
});
更新:我刚测试了这个,它完全有效(喔!)。它也适用于任意级别的嵌套,而不仅仅是两个。
答案 2 :(得分:0)
这是一个可爱的小线程,让我几乎成为我需要的地方。我略微改编了Nickf的代码。目的是检查孩子也会检查父母,取消检查父母也会取消选中所有孩子。
$(“input [type ='checkbox']”)。click(function(){ if(!$(this.checked)){
$(this)
.next('div')
.find("input[type='checkbox']")
.attr("checked", this.checked)
;
}
$(this)
.parent()
.prev('input[type="checkbox"]')
.attr("checked", this.checked || $(this).siblings("input[type='checkbox'][checked]").length > 0
)
;
});
如果取消选中父级,如何调整所有后代?
新的所有东西JQ和javascript..apologies。
答案 3 :(得分:0)
$('.parent').click(function(){
checkBox = $(this).find('input[type=checkbox]');
checkBox.prop("checked", !checkBox.prop("checked")); // inverse selection
});
极限。