0
我查看了jQuery
排序,但我需要排序在兩個兩個級別。使用jQuery在兩個級別上按id排序div
分類兩個級別,頂子級alphabethically
我簡單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.
請點我給我的錯誤。 謝謝!
你是對的!但我只注意到另一個錯誤!我沒有排序第一級! ;-)因此,如果我將紅色移到藍色以上,它不會被排序,但用您的答案我會修復它。謝謝! – lumo