2016-11-30 75 views
0

我有一個動態生成的樹視圖如何動態地循環到UL和LI元素中?

想法是循環到他們只是爲了獲得一些值,但我們不知道每個元素有多少孩子。

<ul> 
    <li>something here</li> 
    <li>something here 
     <ul> 
      <li></li> 
      <li></li> 
      ...more and more childs 
     </ul> 
    </li> 

</ul> 
+1

你應該用遞歸函數來做到這一點。 –

+1

[jQuery查找並列出特定DIV中UL中的所有LI元素]的可能重複(http://stackoverflow.com/questions/7101945/jquery-find-and-list-all-li-elements-within-a -ul-within-a-specific-div) –

+0

如果你使用屬性值的話,它會容易得多 – monssef

回答

2
function getNode($node) { 
    var $children = $node.children(); 
    if ($children.length) { 
    $children.each(function() { 
     getNode($(this)); 
     }) 
     //Do something with the branch 
    } else { 
    //Do something with the leaf 
    } 
} 

getNode($('#your_tree_top_node')); 

該代碼將遞歸通過你的樹,直到它找到葉,並允許您分支的所有葉子被處理後作用於葉子,然後再分支。