我目前正在尝试编写嵌套复选框。我已经想出得到一个子复选框的父复选框,但无论我尝试它都不起作用反之亦然。
我已经尝试过使用.children(),. find()等,只有当它出现在复选框之外时才有效。当$(this)是复选框的对象时,它不会给我前一个元素。如何访问第一个后代对象?谢谢!
HTML:
<ul class='main'>
<li><input type="checkbox" name="settings_overview" value="overview">Settings
<ul class="sub">
<li><input type="checkbox" name="delete" value="add">Add device</li>
<li><input type="checkbox" name="add" value="delete">Delete device</li>
</ul>
</li>
</ul>
JS:
$(document).ready(function () {
$('input:checkbox').click(function () {
var child = $(this).find(':first'); // not working
var parent = $(this).closest("ul").siblings('input:checkbox'); // works
console.log(parent);
console.log(child);
});
});
答案 0 :(得分:1)
有不同的场景,上面的代码在任何时候都不会起作用,如果没有,你可能不得不做后备。 我做了改变,也许这就是你想要实现的目标:
HTML:
<ul class='main'>
<li><input type="checkbox" name="settings_overview" value="overview">Settings
<ul class="sub">
<li><input type="checkbox" name="delete" value="add">Add device</li>
<li><input type="checkbox" name="add" value="delete">Delete device</li>
</ul>
</li>
</ul>
JS:
$(document).ready(function () {
$('input:checkbox').click(function () {
var nextUl = $(this).next("ul"); // not working
var children = nextUl.find("input:checkbox");
// if the clicked element was the child, then we won't get any children using above method
if(children.length == 0){
children = $(this).parents(".sub").find("input:checkbox");
}
var parent = $(this).closest("ul").siblings('input:checkbox'); // works
// Works
//console.log(parent);
//console.log(children);
// If there's a parent, then that means we're in the child
if(parent.length){
var activeChildren = 0;
children.each(function(){
if($(this).is(":checked"))
activeChildren++;
});
if(activeChildren == children.length){
parent.prop("checked", true);
} else {
parent.prop("checked", false);
}
}
// if the clicked element doesn't have any parent, means we clicked on the parent checkbox
if(parent.length == 0){
if($(this).is(":checked")){
children.each(function(){
$(this).prop("checked", true);
});
} else {
children.each(function(){
$(this).prop("checked", false);
})
}
}
});
});
JSFiddle:https://jsfiddle.net/v36xyfdn/14/