如何使用 JavaScript 增长树的 UL 和 ol 列表元素

how to grow the ul and ol list elements of a tree using javascript

本文关键字:UL ol 列表元素 何使用 JavaScript      更新时间:2023-09-26

我必须制作一个树,以便只需单击列表即可动态生成列表。

o 1
o 2
o 3

如果在此,我单击1,应该创建一个子节点可能是11.再次单击1将创建可能是22。

o 1
  o 11
  o 22
o 2
o 3

这个过程将重复多少次,我将点击该元素。 一种情况可能是这样的。

o 1
  o 11
     o 111
     o 222
     o 333
  o 22
  o 33
     o 111
     o 222
     o 333

我完全不知道jquery框架,因为我从未研究过这种语法,我对javascript也有一点了解。 你能在这个方向上指导我,以便我可以融入这样的项目。

我必须生成基于知识的帮助模块,其中包含几个文件夹列表,该列表本身包含文件夹,每个文件夹都有要向代理显示的数据。

例如

folder1
      folder1.1
      folder1.2
      folder1.3
      folder1.4
               folder1.4.1
               folder1.4.2
               folder1.4.3
      folder1.5

此结构将使用树数据结构显示,每个文件夹都包含数据。此文件夹结构将增长/可以动态增长。

不知道这对任何人都有什么用,但这里有一个注释的分步版本:

function foo(e) {
  // Create a new LI
  var newLi = document.createElement('li');
  // Get the element that the click came from
  var el = e.target || e.srcElement;
  // Get it's parent LI if there is one
  var p = getParent(el);
  if (!p) return;
  // Get child ULs if there are any
  var ul = p.getElementsByTagName('ul')[0];
  // If there's a child UL, add the LI with updated text
  if (ul) {
    // Get the li children ** Original commented line was buggy 
//    var lis = ul.getElementsByTagName('li');
    var lis = ul.childNodes;
    // Get the text of the last li
    var text = getText(lis[lis.length - 1]);
    // Update the innerText of the new LI and add it
    setText(newLi, text.replace(/'.'d+$/,'.' + lis.length));
    ul.appendChild(newLi);
  // Otherwise, add a UL and LI  
  } else {
    // Create a UL
    ul = document.createElement('ul');
    // Add text to the new LI
    setText(newLi, getText(p) + '.0');
    // Append the new LI to the new UL
    ul.appendChild(newLi);
    // Add the UL
    p.appendChild(ul);
  }
  function getParent(el) {
    var tagName;
    while (el) {
      tagName = el.tagName.toLowerCase()
      if (tagName == 'li') {
        return el;
      } else if (tagName == 'ul') {
        return;
      }
      el = el.parentNode;
    }
  }
  function getText(el) {
    return el.textContent || el.innerText;
  }
  function setText(el, text) {
    if (typeof el.textContent == 'string') {
      el.textContent = text;
    } else if (typeof el.innerText == 'string') {
      el.innerText = text;
    } else {
      el.innerHTML = '';
      el.appendChild(document.createTextNode(text));
    }
  }
}

一些 HTML 使其工作:

<ul onclick="foo(event)">
  <li>0</li>
  <li>1</li>
  <li>2</li>
</ul>

在Safari 5.1.5,Firefox 3.5.6,IE 6中进行了测试,因此应该几乎可以在任何地方工作。