我可以通过下面的代码升序排序

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>

最佳答案

您的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>

关于javascript - 使用data属性对元素进行升序和降序排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51494063/

10-09 14:57