我有 jQuery 用于分层复选框,看起来像这样
我的 html:
<ul class='tristate'>
<li>
<input type='checkbox' />
<label />
<ul>
<li>
<input type='checkbox' />
<label />
</li>
<li>
<input type='checkbox' />
<label />
<ul>
<li>
<!--can be more in the hierarchy -->
</li>
</ul>
</li>
</ul>
我的 jQuery:
$(document).on("click", ".tristate", function (event) {
var $source = $(event.target);
var checked = $source.prop("checked");
//filter checkboxes that are checked the opposite way to the source
var selector = checked ? ':not(:checked)' : ':checked';
//set all descendant checkboxes to the same value as the source
$source
.siblings("ul")
.find('input:checkbox')
.filter(selector)
.prop({
indeterminate: false,
checked: checked
});
//parents are indeterminate if there are sibling checkboxes
//that are checked the opposite way to the source
var $checkboxesNextToLabel = $lis.children('input:checkbox');
var $checkboxesInsideLabel = $lis.children('label').children('input:checkbox');
var indeterminate = $checkboxesNextToLabel
.add($checkboxesInsideLabel)
.filter(selector).length > 0;
//set state of parent checkboxes
$source
.parentsUntil(".tristate")
.filter('ul')
.prev('label') //label must always be first previous
.prev('input:checkbox') //checkbox must always be second previous
.prop({
indeterminate: indeterminate,
checked: checked && !indeterminate
});
});
这确实适用于我目前在我的应用程序中的标记,但是
我想让代码在遍历到父复选框时更加健壮。具体来说 - .filter('ul').prev('label').prev('input:checkbox')
表示输入必须紧接在标签之前,标签必须紧接在输入。
我想要的是像 closest
这样的命令,它遍历 sibling 而不是祖先,所以我可以写类似 .filter('ul').prevNearest('input:复选框')
编辑 - 警告 对于遇到此问题并希望在复选框层次结构中使用代码的任何人,请当心。我的逻辑有问题。祖 parent 必须检查他们所有的 child 。此代码不执行此操作。
最佳答案
我们可以尝试使用下面的代码来遍历所有的 ul 元素并找到最近的复选框..
var ulCol = $(this).parentsUntil(".tristate").filter('ul');
ulCol.each(function(){
$(this).prevAll('input:checkbox:first').prop({
indeterminate: indeterminate,
checked: checked && !indeterminate
});
});
关于javascript - 通过标签获取最近的前一个兄弟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436592/