Jquery元素匹配检查列表

Jquery check list of elements for a match

本文关键字:检查 列表 元素 Jquery      更新时间:2023-09-26

我有一些使用属性rel分组的复选框。当有人未被检查时,我想检查是否所有人都未被检查,然后做点什么。

场景:我有一个父复选框,所有的子复选框都未选中,父复选框应该是。如果检查了一个或多个,则需要检查父节点。

所有子复选框的类名为child

$('.child').change(function () {
   var groupdId = $(this).attr('rel');
   if($('.child').where('rel', groupId).any('checked', true)) <-- how do I do this?
   {
       //Uncheck the parent
   }
   else {
       //Check the parent.
   }
});

我在这里尝试的是:对于类.child和rel == groupdId的元素,如果其中任何一个被检查,执行x。

$('.child[rel="' + groupId + '"']:checked').length > 0

[rel=...]是针对属性进行选择的一种方式http://api.jquery.com/attribute-equals-selector/

:checked是一个jQuery伪选择器http://api.jquery.com/checked-selector/

var checkbox = $('.child[rel="' + groupId + '"']');
checkbox.prop('checked', !checkbox.is(':checked'));

未经测试,但我认为这将工作。

var $boxes = $('input.child');
$boxes.click(function() {
    var $box = $(this),
        grp = $box.attr('rel'),
        $boxes_in_group = $boxes.filter("[rel='"+ grp +"']");
    if ( $box[0].checked )
        // Check the parent.
    else if ( $boxes_in_group.filter(":checked").length == 0 )
        // Uncheck the parent.
});