2010-11-14 76 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 
});