我查看了使用jQuery
排序,但我需要排序两个级别。
按字母顺序对顶级和子级别进行排序
我的简单HTML
结构就是这样:
<div id="contentObjects">
<div id="Blue" class="sort1">
<div>
Blue
</div>
<div id="Triangle" class="Blue_sort2">
<h3>Triangle</h3>
<div>
internalName: b_triangle
</div>
<div>
displayName: blue Triangle
</div>
<div>
size: 2
</div>
</div>
<div id="Ball" class="Blue_sort2">
<h3>Ball</h3>
<div>
internalName: b_ball
</div>
<div>
displayName: blue Ball
</div>
<div>
size: 5
</div>
</div>
</div>
<div id="Red" class="sort1">
<div>
Red
</div>
<div id="Cube" class="Red_sort2">
<h3>Cube</h3>
<div>
internalName: r_cube
</div>
<div>
displayName: red Cube
</div>
<div>
size: 5
</div>
</div>
</div>
文档准备好后执行此JavaScript
:
function sortAll() {
var arrayOfClassIds = $.map($(".sort1"), function(n, i){
return n.id;
});
var arrayOfSubClassIds;
console.log(arrayOfClassIds);
$.each($('.sort1'), function() {
var _id = $(this).attr('id');
var _parent = $(this);
arrayOfSubClassIds = $.map($("."+_id+"_sort2"), function(n, i){
return n.id;
});
var arrayOfSortedSubClassIds = arrayOfSubClassIds.sort();
console.log(arrayOfSortedSubClassIds);
// start sorting the second level
$.each(arrayOfSortedSubClassIds, function(i, v) {
console.log("appending "+v+" to "+_parent.attr('id'))
// get element with id v and append it to the parent
$(v).appendTo(_parent);
});
});
}
在我的控制台上日志看起来不错:
["Blue", "Red"]
["Ball", "Triangle"]
appending Ball to Blue
appending Triangle to Blue
["Cube"]
appending Cube to Red
所以我的预期是有
Blue with Ball and Triangle, then Red with Cube.
但实际上结果是
Blue with Triangle and Ball, then Red with Cube.
请指出我的错误。 谢谢!
答案 0 :(得分:2)