jQuery检查element是否具有以某些字符串开头的类 [英] jQuery check if element has a class beginning with some string
问题描述
我需要遍历页面中的某些元素,然后对于每个元素,如果它有一个以"C"开头的类,请执行一些操作.
I need to loop through some elements in the page and then, for each one, if it had a class beginning with, for example, "C", do something.
$('#dialog li').each(function(){
if ($(this).hasClass("^C")){
//do something
}
}
听起来可能很愚蠢,但是我应该在if子句上使用什么选择器/方法?
It may sound silly, but what selector/method should I use on the if clause?
推荐答案
用$('#dialog li[class^="C"]')
小心!它只会匹配其类属性以"C"开头的元素,而不匹配那些以C开头的类的元素.例如,它将不匹配<li class="foo Clown">
.
Carefull with $('#dialog li[class^="C"]')
! It will only match elements, whose class attribute starts with "C" not ones with a class starting with C. For example it will not match <li class="foo Clown">
.
AFAIK您想要的是不可能单独使用jQuery的.您将需要遍历这些类,并分别检查每个类.像这样:
AFAIK what you want is not possible mit jQuery alone. You would need to loop through the classes and check each separatly. Something like:
$('#dialog li').filter(function(){
var classes = this.className.split(/\s/);
for (var i = 0, len = classes.length; i < len; i++)
if (/^C/.test(classes[i])) return true;
return false;
}).each( ... )
或者,您应该考虑更改您的方法,并为所有元素提供一个附加的类,并根据该类进行过滤.这样做的好处是它也可以在CSS中使用:
Alternativly you should consider changing your approach, and give all elements an additional class and filter by that. This has the addvantage that it can also be used in CSS:
<li class="Clown Clown-Funny">
<li class="Clown Clown-Sad">
<li class="Clown Clown-Rodeo">
这篇关于jQuery检查element是否具有以某些字符串开头的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!