使用数据属性对元素进行升序和降序排序

时间:2018-07-24 08:34:37

标签: javascript jquery

我可以通过以下代码升序对其进行排序

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}


var sorthtml = getSorted('.instrument', 'data-sortpopular');
$(".vddl-list").html(sorthtml);

但是无法将其降序排序,我尝试了如下操作

sorthtml.toArray().reverse();
$(".vddl-list").html(sorthtml);

如评论所问:以下是示例html

<div class="vddl-list" data-sortpopular="12">
something
</div>
<div class="vddl-list" data-sortpopular="2">
something
</div>
<div class="vddl-list" data-sortpopular="3">
something
</div>

2 个答案:

答案 0 :(得分:2)

您的getSorted函数已损坏,这里有个修复程序,它将可以正常工作!

如果要升序,只需注释最后两行,否则,您将获得反向版本(降序);)

希望这会有所帮助!

function getSorted(selector, attrName) {
    return $(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    });
}


var sorthtml = getSorted('.instrument', 'data-sortpopular');
$(".vddl-list").html(sorthtml);
sorthtml.reverse();
$(".vddl-list").html(sorthtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="instrument" data-sortpopular="12">
something 12
</div>
<div class="instrument" data-sortpopular="2">
something 2
</div>
<div class="instrument" data-sortpopular="3">
something 3
</div>

<div class="vddl-list"></div>

答案 1 :(得分:1)

尝试一下:您可以像下面那样创建反向函数,只是颠倒减法顺序

sorthtml = sorthtml.toArray().reverse(function(a, b){
        var aVal = parseInt(a.getAttribute('data-sortpopular')),
            bVal = parseInt(b.getAttribute('data-sortpopular'));
        return bVal - aVal;
});
$(".vddl-list").html(sorthtml);
相关问题