按动态类对div元素进行分组

时间:2013-11-13 08:58:24

标签: javascript jquery

我有day类动态:

<div class="day day111">a</div>
<div class="day day111">a</div>
<div class="day day112">a</div>
<div class="day day112">a</div>
<div class="day day113">a</div>

我正试图解决这个问题:

<div class="group">
    <div class="day day111">a</div>
     <div class="day day111">a</div>
</div>
<div class="group">
    <div class="day day112">a</div>
    <div class="day day112">a</div>
</div>
<div class="group">
    <div class="day day113">a</div>
</div>

我只能在javascript中执行此操作。我正在尝试循环,但我无法分组。你能帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:3)

尝试

var groups = {};
$('.day').each(function () {
    var className = this.className.match(/(day\d+)/)[1],
        $group = groups[className];
    if (!$group) {
        $group = $('<div />', {
            'class': 'group'
        }).insertAfter(this);
        groups[className] = $group;
    }
    $group.append(this);
})

演示:Fiddle

答案 1 :(得分:0)

看看这个:

$('#box1 >div.day').each(function(){
   var cls = (this.className);

    var group = groups[cls];
    if(!group)
    {
    group = $('<div/>').appendTo('#box2');
    group.addClass('group');

    groups[cls] = group;
    }

    $(this).appendTo(group);
});

http://jsfiddle.net/p3YTS/2/