[英]How can I detect if a label has a specific class?
I have a dropdown menu that contains checkboxes, and more than one can be checked at once. 我有一个包含复选框的下拉菜单,可以一次检查多个复选框。 When a checkbox is selected, it's label's class is set to "checked" and then removed when it is deselected.
选中复选框后,其标签的类别将设置为“选中”,然后在取消选中时将其删除。
Before checkbox is selected: 选中复选框之前:
<label><input type="checkbox" name="gainlosstypes[]" value="Losses" class="upperFilter">Losses</label>
After checkbox is selected: 选中复选框后:
<label class="checked"><input type="checkbox" name="gainlosstypes[]" value="Losses" class="upperFilte">Losses</label>
When it is selected the label element has .toggleClass('checked')
called on it. 选中标签元素后,
.toggleClass('checked')
调用.toggleClass('checked')
。
I need to be able to detect which label's have their class set to "checked" so that I can filter data based on those fields. 我需要能够检测哪个标签的类设置为“选中”,以便可以基于这些字段过滤数据。
If $(this)
is the label element, when I try $(this).hasClass('checked')
it throws an error. 如果
$(this)
是label元素,则当我尝试$(this).hasClass('checked')
它将引发错误。 That's the only way I know to try. 那是我知道尝试的唯一方法。 Is there some other way to tell if a specific label element has a specific class?
还有其他方法可以判断特定标签元素是否具有特定类吗?
Edit: 编辑:
I get these errors when trying to check for the attribute. 尝试检查属性时出现这些错误。 It also happens when I use hasClass:
当我使用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'
Checked is not a css class it is an html attribute. 检查的不是CSS类,而是html属性。 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. 就像@Bojangles所说的,
checked
可以是一个自定义CSS类,但是使用属性而不是自定义css类来检查checked复选框可能更有意义。
EDIT #2: 编辑#2:
PLEASE SKIP PREVIOUS ANSWER AND USE THIS INSTEAD: 请跳过先前的答案并使用以下说明:
You could use the JQuery selector on this: 您可以在此使用JQuery选择器:
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...
}
)
如果标签的属性设置为“ checked”,这将设置为checked,否则您将无法定义并且可以根据此逻辑。
var checked = $(this).attr('checked');
How about 怎么样
if( $(this).attr('class') == "checked" ){
... do something
}
That will check for the class of checked . 那将检查checked的类。 .
。 .
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.