返回ul中的重复项

时间:2012-09-11 18:59:51

标签: jquery jquery-selectors

如何在jquery中构建返回对象的函数,如下所示:

<ul class="clearfix">
  <li data-year="2011" data-month="1">Jan</li>
  <li data-year="2011" data-month="2">Feb</li>
  <li data-year="2012" data-month="3">Mar</li>
  <li data-year="2012" data-month="4">Apr</li>
  <li data-year="2012" data-month="5">May</li>
</ul>

搜索li项目,查找data-year并返回具有相同项目数的对象,如此 {2011:2,2012:3}

2 个答案:

答案 0 :(得分:1)

function obj(ul) {
    return {
               2011: $('li[data-year="2011"]', ul).length,
               2012: $('li[data-year="2012"]', ul).length
           }
}

console.log(obj($('ul')))   

http://jsfiddle.net/x2n7t/2/

更新

var obj = {};

$('ul li[data-year]').each(function(){
   var year = $(this).data('year');
   obj[year] = obj[year] ? obj[year] + 1 : 1
})

http://jsfiddle.net/x2n7t/3/

答案 1 :(得分:0)

检查

var arr = [];
$('ul li').each(function(){
    var y = $(this).attr('data-year');
    if($.inArray(y,arr) < 0)
        arr.push(y);
});
// You build the Array with the List of Items..
//console.log(arr);

// Build the Object Here..

var obj = {};
$.each(arr, function(i){
    var y = arr[i];
    obj[y] = $('ul li[data-year="'+ y + '"]').length;
});
console.log(obj);​​​​​​​​​​​​​​​

以下是DEMO