按类排序div元素(jQuery / Javascript)

时间:2013-06-19 15:56:36

标签: javascript jquery html dom

我想使用jQuery按类(cat1,cat2,cat3等...)对#list中的div元素进行排序。

<section id="list" class="pix_wall pix_load_content isotope" style="position: relative; overflow: hidden; height: 570px; opacity: 1;">
<div class="cat8 entry post-id-34  isotope-item" data-sort="8" style="position: absolute; left: 0px; top: 0px;">
</div>
<div class="cat2 entry post-id-124  isotope-item" data-sort="2" style="position: absolute; left: 380px; top: 0px;">
</div>
<div class="cat7 entry post-id-79 isotope-item" data-sort="7" style="position: absolute; left: 760px; top: 0px;">
</div>
<div class="cat5 entry post-id-87 isotope-item" data-sort="5" style="position: absolute; left: 1140px; top: 0px;">
</div>
<div class="cat3 entry post-id-95 isotope-item" data-sort="3" style="position: absolute; left: 1520px; top: 0px;">
</div>
<div class="cat1 entry post-id-99 isotope-item" data-sort="1" style="position: absolute; left: 0px; top: 285px;">
</div>
</section>

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

var sorted_entries = $('.entry').sort(function (a, b) { 
    var _a = /cat(\d+)/.exec(a.className)[1];
    var _b = /cat(\d+)/.exec(b.className)[1];

    if (_a < _b) {
        return -1;
    } else if (_a > _b) {
        return 1;
    } else {
        return 0;
    }
});

$('section').html(sorted_entries);

Fiddle