如何使用 JavaScript 增长树的 UL 和 ol 列表元素
how to grow the ul and ol list elements of a tree using javascript
我必须制作一个树,以便只需单击列表即可动态生成列表。
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中进行了测试,因此应该几乎可以在任何地方工作。
相关文章:
- 在单独的ul's
- 将所选类别循环到ul>李用加载更多按钮
- 使用jquery动态创建ul-li
- 使用下拉列表筛选列表(ul>li)
- 如何附加<ul><李>元素位于某个特定条件的父元素列表之间
- :not选择器不适用于ul类-备选方案
- 在验证器中添加自定义规则以检查<ul>具有元素
- 在JQuery中隐藏和显示ul中的特定元素
- 使用 jquery 获取外部父 UL
- 隐藏/显示包含单词的ul li项目.但只能入住李的子女
- 如何在点击时显示ul项目
- 限制ul元素中显示的项目
- ul-li专属功能
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- 如何使用 JavaScript 增长树的 UL 和 ol 列表元素
- 列出OL&UL支持addHTML
- jQuery可以模拟onchange事件吗?一个选择框,但对于UL/OL
- CKEditor ul ol enclosure
- JQuery检查单击的li是否有子ol/ul
- 在Javascript中切换ul和ol的任何方法