2009-11-01 51 views

回答

1

有很多方法來traverse使用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