如何获得完整的后代层次结构?

时间:2009-11-01 01:45:20

标签: javascript jquery

鉴于父母,如何获得其后代以保持其等级。

parent > des1 > des2 > des3

parent.find('*')只是按顺序返回,它会给出

find('des1, des2. des3') 

我期待的是

find('des1 des2 des3')

1 个答案:

答案 0 :(得分:1)

使用jQuery的traverse有很多方法。这是一种方法。我正在使用以下标记:

<div id="demoParent">
  <div id="des1">
    <div id="des2"> 
      <div id="des3">
        hello world
      </div>
    </div>
  </div>
</div>

我使用这个递归函数遍历并返回一个带有层次结构的字符串:

function getHierarchy(selector) {
    // temp variable to hold the hierarchy as an array
    var hierarchy = [];
    // if selector element has a :first-child...
    while ($(selector).children(':first-child').length > 0) {
        // then push it into the array and then traverse into the :first-child
        hierarchy.push($(selector).children(':first-child').attr('id'));
        selector = $(selector).children(':first-child');
    }
    // when there are no more :first-child elements, return string
    // formatted like elemA > elemB > elemC > elemD
    return hierarchy.join(' > ');
}

当我这样调用此代码时:alert(getHierarchy('#demoParent'));

我将此结果作为提醒:des1 > des2 > des3