Как получить полноценного потомка hiearchy? - PullRequest
2 голосов
/ 01 ноября 2009

Учитывая родителя, как я могу получить его потомков, чтобы сохранить их иерархию.

parent > des1 > des2 > des3

parent.find('*') просто возвращает не в порядке, это дает

find('des1, des2. des3') 

что я ожидал было

find('des1 des2 des3')

1 Ответ

1 голос
/ 03 ноября 2009

Существует множество способов пройти с помощью jQuery. Вот один из подходов. Я использую следующую разметку:

<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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...