按两个属性对jQuery列表进行排序 [英] Sort jQuery list by two attributes
问题描述
我有这个标记:
#a(data-row="2", data-col="3") a
#b(data-row="1", data-col="1") b
#c(data-row="1", data-col="3") c
#d(data-row="2", data-col="2") d
#e(data-row="1", data-col="2") e
#f(data-row="2", data-col="1") f
如你所见,它定义了一个元素网格(3列和2行)。
As you can see, it defines a grid of elements (3 columns and 2 rows).
我需要用jQuery获取这个项目列表并按顺序排序行
和 col
。
I need to get this list of items with jQuery and order them by row
and by col
.
结果提供的标记应该是:
The result of the markup provided should be:
b, e, c, f, d, a
我可以按行成功订购,但后来我不知道通过col订购它们的最佳方式是什么:
I can successfully order them by row but then I don't know what is the best way to order them by col:
var gridElements = $('div');
gridElements.sort(function (a, b) {
var contentA =parseInt( $(a).attr('data-row'));
var contentB =parseInt( $(b).attr('data-row'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});
CodePen: http://codepen.io/FezVrasta/pen/bVEezw
我想我应该按数据行过滤列表然后在每个组上再次运行 sort
但是如何?
I think I should filter the list by data-row and then run sort
again on each group, but how?
推荐答案
第二个值只有在第一个值相等时才适用,所以这应该适合你:
The second value is only applicible if the first values are equal, so this should do it for you:
var gridElements = $('div');
gridElements.sort(function (a, b) {
var contentA =parseInt( $(a).attr('data-row'));
var contentB =parseInt( $(b).attr('data-row'));
//check if the rows are equal
if (contentA === contentB) {
var colA = parseInt( $(a).attr('data-col'));
var colB = parseInt( $(b).attr('data-col'));
//do the same as your already doing but using different data, from above
return (colA < colB) ? -1 : (colA > colB) ? 1 : 0;
}
else {
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
}
});
这篇关于按两个属性对jQuery列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!