是否可以通过匹配data-id对多个div进行分组并按另一个数据属性进行排序?这可以用下划线或普通javascript完成吗?
div当前布局和期望输出值
<div id="parentID">
<div data-id="71" data-orderby="2" class="child">ID: 71 Order 2</div>
<div data-id="71" data-orderby="3" class="child">ID: 71 Order 3</div>
<div data-id="71" data-orderby="1" class="child">ID: 71 Order 1</div>
<div data-id="62" data-orderby="2" class="child">ID: 62 Order 2</div>
<div data-id="62" data-orderby="1" class="child">ID: 62 Order 1</div>
<div data-id="59" data-orderby="1" class="child">ID: 59 Order 1</div>
<div data-id="59" data-orderby="3" class="child">ID: 59 Order 3</div>
<div data-id="59" data-orderby="2" class="child">ID: 59 Order 2</div>
</div>
<div id="parentID">
<div data-id="71" data-orderby="1" class="child">ID: 71 Order 1</div>
<div data-id="71" data-orderby="2" class="child">ID: 71 Order 2</div>
<div data-id="71" data-orderby="3" class="child">ID: 71 Order 3</div>
<div data-id="62" data-orderby="1" class="child">ID: 62 Order 1</div>
<div data-id="62" data-orderby="2" class="child">ID: 62 Order 2</div>
<div data-id="59" data-orderby="1" class="child">ID: 59 Order 1</div>
<div data-id="59" data-orderby="2" class="child">ID: 59 Order 2</div>
<div data-id="59" data-orderby="3" class="child">ID: 59 Order 3</div>
</div>
您可以根据id
和orderby
属性对div
进行排序。
$(function() {
$("#parentID div").sort((a,b) => {
return $(b).data('id') - $(a).data('id') || $(a).data('orderby') - $(b).data('orderby');
}).appendTo('#parentID');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parentID">
<div data-id="71" data-orderby="2" class="child">ID: 71 Order 2</div>
<div data-id="71" data-orderby="3" class="child">ID: 71 Order 3</div>
<div data-id="71" data-orderby="1" class="child">ID: 71 Order 1</div>
<div data-id="62" data-orderby="2" class="child">ID: 62 Order 2</div>
<div data-id="62" data-orderby="1" class="child">ID: 62 Order 1</div>
<div data-id="59" data-orderby="1" class="child">ID: 59 Order 1</div>
<div data-id="59" data-orderby="3" class="child">ID: 59 Order 3</div>
<div data-id="59" data-orderby="2" class="child">ID: 59 Order 2</div>
</div>
使用这个脚本
$("#parentID div.child").sort(function(a, b) {
return $(a).data("id") - $(b).data("id");
}).appendTo("#parentID");