0

我必须制作一棵树,以便它允许通过单击它来动态生成列表。例如

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

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

4

1 回答 1

1

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

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 中测试,所以应该可以在任何地方工作。

于 2012-05-15T10:13:27.337 回答