0

我有一个包含复选框的下拉菜单,一次可以检查多个。当一个复选框被选中时,它的标签类设置为“选中”,然后在取消选中时将其删除。

选中复选框之前:

<label><input type="checkbox" name="gainlosstypes[]" value="Losses" class="upperFilter">Losses</label>

选中复选框后:

<label class="checked"><input type="checkbox" name="gainlosstypes[]" value="Losses" class="upperFilte">Losses</label>

当它被选中时,标签元素已.toggleClass('checked')调用它。

我需要能够检测哪些标签的类设置为“已检查”,以便我可以根据这些字段过滤数据。

如果$(this)是标签元素,当我尝试$(this).hasClass('checked')它时会引发错误。这是我知道尝试的唯一方法。是否有其他方法可以判断特定标签元素是否具有特定类?

编辑:

尝试检查属性时出现这些错误。当我使用 hasClass 时也会发生这种情况:

> $(".multiSelectOptions :checkbox")[1].attr('checked')
TypeError: Object #<HTMLInputElement> has no method 'attr'
> $(".multiSelectOptions :checkbox").parent('label')[1].attr('checked')
TypeError: Object #<HTMLLabelElement> has no method 'attr'
4

3 回答 3

1

Checked is not a css class it is an html attribute. thus you should check for the attribute not the class.

You should try :

if($(this).attr('checked') != null)
{
    //do stuff here
}

EDIT:

Like @Bojangles said checked could be a custom CSS class but it would probably make more sense to check for checked checkbox with the attribute rather than a custom css class.

EDIT #2:

PLEASE SKIP PREVIOUS ANSWER AND USE THIS INSTEAD:

You could use the JQuery selector on this:

For exemple:

$('.checked')//this would get you all the element with the class 'checked'

//if you want to check if you have any check element:

if($('.checked').length > 0)
{
    //do stuff here
}

//To loop trought all the element that are 'checked'

$('.checked').each(
function(index)
{
    $(this).removeClass('checked');
    //do stuff here for exemple...
}
)
于 2013-09-13T15:22:46.820 回答
-2

This will set checked if the label has the attribute 'checked' set, otherwise you'll get undefined and can base your logic off this.

var checked = $(this).attr('checked');
于 2013-09-13T15:22:31.463 回答
-2

怎么样

if( $(this).attr('class') == "checked" ){
    ... do something
}

这将检查 checked 类。. .

于 2013-09-13T15:26:43.447 回答