gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:26:29 24 4
gpt4 key购买 nike

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

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 - 使用数据属性对元素进行升序和降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51494063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com