代码之家  ›  专栏  ›  技术社区  ›  Gracie williams

使用data属性对元素集进行升序和降序排序

  •  0
  • Gracie williams  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  2
  •   sjahan    6 年前

    你的 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>
        2
  •  1
  •   Bhushan Kawadkar    6 年前

    试试这个:你可以创建一个像下面这样的函数,只需颠倒减法的顺序

    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);