我有一个 div 列表,分为两组。每个 div 用 class="container-x" 编号为 1、2、0、1、2、0... 等。
对 div 进行排序后,位置发生了变化,但我希望他们仍然保留这个编号。
排序后如何更新他们的班级名称?
马基普:
<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;
}
};
我在这里创建了一个小提琴。