2010-11-14 78 views
1
$("input").each(function() { 
    if ($(this).hasClass('valid')) { 
     // Do something 
    } 
}); 

上述代码确定input是否具有指定的类。然而,我怎么能改变if语句来使它做某些事情时input不是有一个指定的类?选择不包含jQuery指定类的元素?

回答

3

您可以用!否定这样的内做到这一点:

$("input").each(function() { 
    if (!$(this).hasClass('valid')) { 
     // Do something 
    } 
}); 

或者选择寿命时只需使用:not() SE的元素,像这样:

$("input:not(.valid)").each(function() { 
    // Do something 
}); 

这意味着你的原代码,也可以更薄(用于当确实有类),像这样:

$("input.valid").each(function() { 
    // Do something 
}); 
1

使用负操作!

$("input").each(function() { 
    if (!($(this).hasClass('valid'))) { // pass this statement if the valid class is not present 
     // Do something 
    } 
}); 
2

您还可以使用:not selector

$("input:not(.valid)").each(function() { 
    //Do Something 
});