检查一个类是否存在于一组选定的元素中

Check if a class exist within a group of selected elements

本文关键字:于一组 元素 存在 是否 一个 检查      更新时间:2023-09-26

我选择了一组行,我现在试图确定它们是否包含特定的类。

我已经在hasClassfind上尝试过,但没有成功:

var group = $('table').find('[data-group="group1"]');
//this doesn't work, it always enters in the condition
if(group.find('.active')){
    alert("Founded?");
    group.addClass('green');    
}
http://jsfiddle.net/kAHyA/1/

我也尝试过if(group.find('.active').length),但仍然没有得到正确的结果:

http://jsfiddle.net/kAHyA/3/

你可以用hasClass方法做到这一点http://api.jquery.com/hasClass/

if(group.hasClass('active')){
...
}

如果你试过:

if(group.hasClass('.active')){
...
}

它肯定不起作用,注意与"。"

试试这个,

if(group.filter('.active').length)

只是想检查tr是否具有active类并具有数据属性,因此只需一个简单的选择器就足够了。

var matches = $('table').find('.active[data-group="group1"]'); //This will give you all the trs with the attribute and class active.
if(matches.length > 0)
{
   alert('Found Match');
   matches.addClass('green');
}

如果你只是想直接应用class,只需链接它:

$('table').find('.active[data-group="group1"]').addClass('green');
演示

你可以这样做-

if(group.is('.active')){
    group.addClass('green');    
}
演示---> http://jsfiddle.net/kAHyA/6/

.find()的问题是它总是返回一个jQuery对象,这就像任何其他对象(除了null)一样是正确的。

您要检查长度:if( group.find(".active").length > 0)