javascript - 如何动态循环到 UL 和 LI 元素中?

标签 javascript jquery html css

我有一个动态生成的 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/

相关文章:

javascript - 使用 JQuery 导航无根 dom

html - 幻灯片下拉打开

javascript - JsTree:使用 "open"插件更改文件夹的 "types"图标

php - Javascript/AJAX 在除 IE 之外的所有环境中都可以正常工作

javascript - 无法在 jquery 的 div 中显示 ul li 的计数

javascript - 使用 JQuery 在 2 个 html 文件中使用来自同一 js 文件的变量

javascript - 从html数据中获取Column数据

javascript - 如何在 Jquery 中删除克隆的 div

javascript - 在多个复选框中选中全部或取消选中全部

javascript - 网站加载时可以从确定的 div 开始吗?