如何创建按父母/子女数量排序的数组?

时间:2014-05-14 22:08:04

标签: javascript jquery arrays

你怎么能得到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"]

2 个答案:

答案 0 :(得分:3)

这有效:

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;
}

DEMO

答案 1 :(得分:1)

<强> jsFiddle Demo

使用父引用,递归遍历子项并记录深度。按深度排序这些记录,然后返回类名称数组。 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"]