Jquery检查匹配元素的列表

时间:2011-12-01 00:11:59

标签: javascript jquery

我有一些使用属性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 AND rel == groupdId的元素,如果选中其中任何一个,请执行x。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

未经测试,但我认为这样可行。

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.
});
相关问题