javascript - 选中/取消选中 parent 和 child

标签 javascript jquery

你能写出更好的代码吗?我需要根据 parent 检查/取消选中所有子女的检查,然后在检查 child 时,请检查 parent ,当所有子女都没有选中的未选中 parent 。

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

关于javascript - 选中/取消选中 parent 和 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/158544/

相关文章:

javascript - 为什么参数读取为true?

javascript - 如何只从没有列名和括号的对象数组中获取值?

javascript - 填充数组失败

javascript - HTML 5 Canvas : Uploaded image colour picker

javascript - 使用backbone和Express渲染模板

javascript - 如何将json从一种格式转换为另一种格式?

javascript - 在 JavaScript 函数之间传递 JSON 值

javascript - Handlebars 似乎没有调用我的 Controller 功能

javascript - 获取每个offsetParent或总offSetTop和总offSetLeft

javascript - jQuery Deferred 的 $.when() 和 failed() 回调参数