选中/取消选中父母和孩子

时间:2020-03-06 14:59:08  来源:igfitidea点击:

我们可以编写更好的代码吗?我需要检查/根据父母当孩子被检查,检查父,取消所有孩子的时候孩子的一切都选中取消选中父。

$(".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);
});

解决方案

$(".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
    );
});

哇,我很困惑。看起来好像我们在其中具有其他输入的输入? ...这没有任何意义。我认为这是结构的样子,所以我继续。

<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.
        )
    ;
});

更新:我刚刚测试了它,它完全可以工作(呜!)。它也可以根据需要使用多个级别的嵌套,而不仅仅是两个。

这是一个可爱的小话题,使我几乎可以适应我的需要。我稍微修改了尼克的代码。目的是检查孩子也将检查父母,取消选中父母也将取消所有孩子。

$(" input [type ='checkbox']")。click(function(){
如果(!$(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的所有新特性。