[英]How can I detect if a label has a specific class?
我有一個包含復選框的下拉菜單,可以一次檢查多個復選框。 選中復選框后,其標簽的類別將設置為“選中”,然后在取消選中時將其刪除。
選中復選框之前:
<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')
調用.toggleClass('checked')
。
我需要能夠檢測哪個標簽的類設置為“選中”,以便可以基於這些字段過濾數據。
如果$(this)
是label元素,則當我嘗試$(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'
檢查的不是CSS類,而是html屬性。 因此,您應該檢查屬性而不是類。
你應該試試 :
if($(this).attr('checked') != null)
{
//do stuff here
}
編輯:
就像@Bojangles所說的, checked
可以是一個自定義CSS類,但是使用屬性而不是自定義css類來檢查checked復選框可能更有意義。
編輯#2:
請跳過先前的答案並使用以下說明:
您可以在此使用JQuery選擇器:
舉個例子:
$('.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');
怎么樣
if( $(this).attr('class') == "checked" ){
... do something
}
那將檢查checked的類。 。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.