我有一个动态生成的 TreeView
想法是通过循环获取一些值,但我们不知道每个元素有多少个子元素。
<ul>
<li>something here</li>
<li>something here
<ul>
<li></li>
<li></li>
...more and more childs
</ul>
</li>
</ul>
最佳答案
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'));
此代码将递归遍历您的树,直到找到叶子,并允许您先对叶子进行操作,然后在该分支的所有叶子都已处理后对分支进行操作。
关于javascript - 如何动态循环到 UL 和 LI 元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878345/