1

我有这样的清单。

<li data-pet="cat"></li>
<li data-pet="cat"></li>
<li data-pet="cat"></li>
<li data-pet="dog"></li>

如果相同的值出现不止一次,使用 jQuery 如何获取数据属性的值以进行计数。

然后我想将一个跨度附加到具有该值的第一个列表元素。

结果应该是这样的。

<li data-pet="cat"><span class="first"></span></li>
<li data-pet="cat"></li>
<li data-pet="cat"></li>
<li data-pet="dog"></li>

谢谢你的帮助。

4

4 回答 4

2

一个可能的实现

(function() {  
    var pets = {};
    $('li[data-pet]').each(function() {
        var li = $(this),
            pet = li.data('pet');

        if (!pets[pet]) {  
            pets[pet] = { firstnode: li, count : 1 }
        }
        else {
            pets[pet]['count'] = pets[pet]['count'] + 1;
        }
    });

    $.map(pets, function(obj) {     
        if (obj.count > 1) {
          obj.firstnode.append('<span class="first">'+ obj.count +'</span>');
        }
    });
}());

html

<li data-pet="cat">cat</li>
<li data-pet="cat">cat</li>
<li data-pet="cat">cat</li>
<li data-pet="dog">dog</li>
<li data-pet="elephant">elephant</li>
<li data-pet="elephant">elephant</li>

小提琴示例:http: //jsfiddle.net/HJ6gF/6/

于 2012-04-16T15:15:16.483 回答
0

一种方法是(你应该根据你的情况优化/整理它):

var selector = "cat";
var selectorCount = 0;

$("li[data-pet="+selector+"]").each(function() {
    selectorCount++;
});

if(selectorCount > 1) {
    $("li[data-pet="+selector+"]").each(function() {
        $(this).html("<span class=\"first\"></span>");
        break;
    });
}
于 2012-04-16T15:02:15.240 回答
0
var tarr = [];
$('li').each(function() {
   tarr.push($(this).attr('data-pet'))
});
var count = $.unique(tarr).length;
于 2012-04-16T15:02:18.017 回答
0
<li data-pet="cat"/>
<li data-pet="cat"/>
<li data-pet="cat"/>
<li data-pet="dog"/>

<script type="text/javascript">

    var dataPets = [];

    $('li').each( function( index )
    {
        if ( $.inArray( $(this).attr( "data-pet" ) , dataPets ) )
        {
            $(this).append( "First" );
        }

        dataPets[index] = $(this).attr( "data-pet" );
    });

</script>
于 2012-04-16T15:09:49.610 回答