1

我有多个类的跨度标签:

 <div class="container">
 <span class="otherclass item3">Text</span>
 <span class="otherclass item1">Blah</span>
 <span class="item2">Stuff</span>
 </div>

我有兴趣计算以“item”为前缀的类的 span 元素的数量。我知道我可以这样做:

 $(document).on('click','span',function(){
 var ItemTot = $(this).closest('.container').find('[class*= item]').length;
 alert(ItemTot);
 }

...计算具有多个类的跨度元素的数量,但这不会计算单个类跨度。我可以用下面的代码得到它,但肯定有一种更简洁的方法来计算这两种情况吗?

 .find('[class^=item]').length;
4

2 回答 2

1

CSS 缺少“单词开头”属性选择器。(它具有以 [ ]开头的属性^=,并且具有与 [ ~=] 匹配的单词,但不是与单词开头匹配的它们的组合。)

所以你必须手动完成:Live Copy | 直播源

var ItemTot = $(this).closest('.container').find('[class*=item]').filter(function() {
    return this.className.match(/\bitem/);
}).length;

这将查找其class属性包含item(任何位置)的任何元素,然后仅根据item单词开头的元素进行过滤。

于 2013-06-19T12:02:39.500 回答
-1

你最干净的选择是$('span[class~="item"]').length

alert($('span[class~="item"]').length);

示例:http: //jsfiddle.net/sPNLW/1/

请参阅http://api.jquery.com/category/selectors/attribute-selectors/$('span[class~="item"]')查找spans包含属性中item任何位置的所有内容。class

于 2013-06-19T12:03:41.813 回答