<div id="customerServices">
<input id="s9" type="checkbox" /> Parent element<br/>
<input id="s15" class="parent-s9" type="checkbox" /> Child element<br/>
<input id="s16" class="parent-s9" type="checkbox" /> Child element<br/>
<br/><br/><br/>
<input id="s10" type="checkbox" /> Parent element2<br/>
<input id="s151" class="parent-s10" type="checkbox" /> Child element2<br/>
<input id="s161" class="parent-s10" type="checkbox" /> Child element2<br/>
<br/><br/><br/>
<input id="s101" type="checkbox" /> Parent element3<br/>
<input id="s102" type="checkbox" /> Parent element4<br/>
</div>
页面上有一些复选框。我需要:父母和子女复选框
- 检查所有孩子是否选中父母。
- 如果所有孩子都未选中,请取消选中父母。
- 如果至少有一个孩子被选中,则检查父代。
这是一些一些代码,但它不工作
$('input[type=checkbox]').change(function() {
var id = $(this).attr('id');
var children = $('.parent-' + id);
//Is this a child
if (children.length)
{
//Is it checked
if ($(this).is(':checked'))
{
//Find the parent
var className = $(this).attr('class');
var pId = className.replace("parent-","");
//If the parent is not checked, then check this parent
if (!$(pId).is(':checked'))
$(pId).attr('checked','checked');
}
//Is it NOT checked
else{
//Do other childs are not checked too?
//var className2 = $(this).attr('class');
//$(className2)
}
}
//If this is a parent, then check all childs
esle{
children.attr('checked', $(this).attr('checked'));
}
});
完美!谢谢。 – Alexandre 2011-03-01 14:13:07
很高兴帮助:) – CoolEsh 2011-03-01 14:19:07
也许简化这样的功能片段:'parentClicked:function(){var parentCheck = this.checked; $('#customerServices input:checkbox [class =“parent-'+ $(this).attr('id')+'”]')。each(function(){this.checked = parentCheck;}); },' – 2011-03-01 17:58:03