[英]How to create an array ordered by amount of parents/children?
你怎么能得到javascript(或jquery,如果它更容易)返回一個數組,從父母最少的元素開始,然后是第二少,第三少......依此類推
所以這樣的DOM就像下面這樣
<div class="first">
<div class="second">
<div class="third"></div>
<div class="fourth">
<div class="fifth"></div>
</div>
</div>
<div class="sixth"></div>
<div class="seventh">
<div class="eighth"></div>
</div>
<div class="ninth"></div>
</div>
<div class="tenth"></div>
會返回這樣的數組......
["first", "tenth", "second", "sixth", "seventh", "ninth", "third", "fourth", "eighth", "fifth"]
這有效:
var $first = $('body').children('div'), // Finds the first level
output = []; // Stores the results
while ($first.length != 0) { // While we still can go deeper
output = $.merge(output, assemble($first)); // Get the classes on this level
$first = $first.children('div'); // Dive deeper
}
console.log(output); // Output the results
function assemble(l) { // Collects classes at a level
var arr = [];
$.each(l, function() {
arr.push($(this).attr('class'));
});
return arr;
}
使用父引用,遞歸遍歷子項並記錄深度。 按深度排序這些記錄,然后返回類名稱數組。 jQuery不那么詳細,這里顯示的是jQuery從容器開始執行此操作的擴展方法。
$.fn.classByDepth = function(){
var elements = [];
(function children(top,depth){
top.children().each(function(){
var element = {
name: this.className,
depth: depth
};
elements.push(element);
children($(this),depth+1);
});
})(this,1);
elements.sort(function(left,right){
if(left.depth<right.depth)return -1;
if(left.depth>right.depth)return 1;
return 0;
});
var ordered = [];
$.each(elements,function(){
ordered.push(this.name);
});
return ordered;
};
用過的:
//assuming that #container was a div containing your example html structure
console.log($("#container").classByDepth());
//["first", "tenth", "second", "sixth", "seventh", "ninth", "third", "fourth", "eighth", "fifth"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.