排序div后保持编号

时间:2013-10-25 10:03:09

标签: jquery

我有一个div列表,它分为两组。每个div的编号为1,2,0,1,2,0 ......等,类=“container-x”。

排序之后div已改变位置,但我希望他们仍然保留这个编号。

如何在排序后更新其班级名称?

Markyp:

<div class="container container-1">
    <div class="terminal" data-price="195">
        <h3>195</h3>
    </div>
    I should come in 2nd in group 1 which is displayed first.
</div>

<div class="container container-2">
    <div class="terminal" data-price="220">
        <h3>220</h3>
    </div>
    I should come in 3rd in group 1 which is displayed first.
</div>

<div class="container container-0">
    <div class="terminal" data-price="740">
        <h3>740</h3>
    </div>
    I should come in 2nd in group 2 which is displayed last.
    <div class="anotherGroup">Group 2</div>
</div>

<div class="container container-1">
    <div class="terminal" data-price="140">
        <h3>140</h3>
    </div>
    I should come in 1st in group 2 which is displayed last.
    <div class="anotherGroup">Group 2</div>
</div>

<div class="container container-2">
    <div class="terminal" data-price="130">
        <h3>130</h3>
    </div>
    I should come in 1st in group 1 which is displayed first.
</div>

脚本:

var _count = 0;

$('.terminal').sort(function (a, b) {
    return $(a).data('price') - $(b).data('price');
}).map(function () {
    return $(this).closest('.container');
}).each(paint);

function paint(_, container) {
    if ($(container).children('.anotherGroup')[0]) {
        $(container).parent().append(container);
    } 
    else {
        var next = paint.next;
        if (next) {
            $(container).insertAfter(next);
        } 
        else {
            $(container).parent().prepend(container);
        }
            paint.next = container;
        }
    };

我创建了一个fiddle here

1 个答案:

答案 0 :(得分:0)

您可以这样做来更新班级编号:

$('.container').each(function (i, v) {
    $(this).attr('class', 'container container-' + i);
});

但我同意Rory McCrossan的评论,使用增量id或类属性并不是一个好习惯。

例如,如果您仅使用增量类名进行选择,那么jQuery的:eq() Selector可能会派上用场:

// this will select the second 'container' div
var $div = $('.container:eq(1)');