问题描述
|
我有这个嵌套的列表结构。我的树可以升到n级。
我想要一个JQuery的选择器,它只能选择父级(如果选中子级)。
<ul id=\"treeFeatureList\">
<li>
<input type=\"checkBox\" name=\"selectedRole\">
Application Manager
<ul>
<li>
<input type=\"checkBox\" name=\"selectedRole\">
Application Manager Panel
</li>
<li>
<input type=\"checkBox\" name=\"selectedRole\">
Client Role
<ul>
<li>
<input type=\"checkBox\" name=\"selectedRole\">
Client Task 1
</li>
<li>
<input type=\"checkBox\" name=\"selectedRole\">
Client Task 2
</li>
</ul>
</li>
</ul>
</li>
</ul>
我想要的是:如果选中了客户端Task1或Task2,则也检查了客户端角色和应用程序管理器。绝对不是Application Manager Panel(应保持未选中状态)。
感谢您做出这个神奇的选择器。
解决方法
$(\'input[type=\"checkbox\"]\').change(function() {
if ($(this).is(\':checked\')) {
$(this).parents(\'ul\').siblings(\'input:checkbox\').attr(\'checked\',true);
}
else
{
$(this).parents(\'ul\').siblings(\'input:checkbox\').attr(\'checked\',false);
}
});
这是一个演示。
, .closest()
和.siblings()
的组合应该可以为您提供所需的东西。您将要选择选中的输入的最接近的祖先,它是具有“父”复选框的同级,然后遍历该复选框。代码看起来像这样:
$(\'input:checkbox\').change(function() {
//if you are using < jQuery 1.6,use .attr() instead of .prop()
if (this.checked) {
$(this).closest(\'ul\').siblings(\'input:checkbox\').prop(\'checked\',true);
}
});
这是一个现场演示->
, $(\'input[type=\"checkbox\"]\').change(function() {
if ($(this).is(\':checked\')) {
$(this).parents(\'ul\').siblings(\'input:checkbox\').attr(\'checked\',true);
} else {
//if any of the sibling is checked,do not uncheck the main category
var isSiblingChecked = false;
$(this).parent().siblings().each(function() {
if (($(this).find(\'input[type=\"checkbox\"]\').is(\':checked\'))) {
isSiblingChecked = true;
}
});
if (isSiblingChecked == false) {
$(this).parents(\'ul\').siblings(\'input:checkbox\').attr(\'checked\',false);
}
}
});