在应用程序中,我在元素中添加了一个类名userNote
。 userNote
将numbers
作为帖子固定,如下所示:userNote1
用户可以多次选择相同的元素。所以,我想知道该元素具有多个class
名称,这些名称以相同的模式开头,对我来说是“userNote'。
我可以像这样过滤:
$('body').find('*').filter(function () {
return this.className.match(/\buserNote/);
//it returns the value, but i don't know how many class name it has!
});
但我要求elements
只有多个class
名称具有相同的统计名称。
答案 0 :(得分:2)
最简单的方法是在空格上拆分className
,然后循环结果,查找从字符串开始在数组中获得多个条目的元素。
// Start out with a set of elements that have "userNote" anywhere
// in the class, then filter based on the more detailed criteria
var matches = $('[class*=userNote]').filter(function () {
return this.className.split(' ').reduce(function(p, c) {
return c.substring(0, 8) === "userNote" ? p + 1 : p;
}, 0) > 1;
});
现在,matches
包含一组元素,这些元素包含多个以userNote
开头的类。
(使用ES5功能Array#reduce
,但可以为旧版浏览器填充,或者您只需使用简单的for
循环。)
示例:
// Start out with a set of elements that have "userNote" anywhere
// in the class, then filter based on the more detailed criteria
var matches = $('[class*=userNote]').filter(function () {
return this.className.split(' ').reduce(function(p, c) {
return c.substring(0, 8) === "userNote" ? p + 1 : p;
}, 0) > 1;
});
// Show results
$("<p>Text of matching elements:<br>" + matches.map(function() {
return $(this).text();
}).get().join("<br>") + "</p>").appendTo(document.body);
<div class="userNote">one</div>
<div class="userNote userNote2">two</div>
<div class="userNote userNote2 userNote3">three</div>
<div class="foo">none</div>
<div class="foo userNote userNote2 userNote3 userNote4 bar">four and other classes</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
答案 1 :(得分:-1)
尝试以下选择器
$("p[class*=userNote]").css('color', 'blue');
答案 2 :(得分:-1)
试试这个, 它将使用 userNote 选择所有元素并具有突出显示类
$('body').find('[class*=userNote].highlight').length
我希望这正是你所需要的