0
我有一個divs列表,它被分爲兩組。每個div都被編號爲1,2,0,1,2,0 ...等等,其中class =「container-x」。排序div後保持編號
排序後的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。
我以前說過,我再說一遍,不要使用增量'id'或'class'屬性。這會導致維護問題,特別是在內容被動態修改時。 –
我同意@RoryMcCrossan。如果你想保持樣式的類,然後考慮切換到使用':nth-child'選擇器:http://css-tricks.com/how-nth-child-works/ – gvee